【问题标题】:Django update() is not working as expectedDjango update() 没有按预期工作
【发布时间】:2021-06-09 08:21:50
【问题描述】:

我有一个功能可以在触发时更改模型的详细信息。我无法让它完成我打算让它完成的工作。 我不知道为什么会这样。 任何帮助将不胜感激。

错误代码:

    @login_required(login_url='/login/')
    def move_students(request):
        try:
            Klass.objects.filter(school=request.user.school,name=1).update(name=2)
        except Exception as e:
            messages.info(request,f'erroerd at {e}')
        return redirect('/')

型号:

    class Klass(models.Model):
        name = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5),], help_text='E.g 1,2,3, 4')
        school = models.ForeignKey(School,on_delete=models.CASCADE)
        def __str__(self):
            return str(self.name)
        class Meta:
            verbose_name_plural = 'Classes'
            unique_together = ("school", "name")

堆栈跟踪:

    Traceback (most recent call last):
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
        response = get_response(request)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
        return view_func(request, *args, **kwargs)
      File "D:\Python\Django\Completed Projects\lib_system\Library-System\libman\views.py", line 29, in move_students
        Klass.objects.filter(school=request.user.school,name=1).update(name=2)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 784, in update
        rows = query.get_compiler(self.db).execute_sql(CURSOR)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1522, in execute_sql
        cursor = super().execute_sql(result_type)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql
        cursor.execute(sql, params)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 98, in execute
        return super().execute(sql, params)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 66, in execute
        return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
        return executor(sql, params, many, context)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
        return self.cursor.execute(sql, params)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 90, in __exit__
        raise dj_exc_value.with_traceback(traceback) from exc_value
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
        return self.cursor.execute(sql, params)
      File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
        return Database.Cursor.execute(self, query, params)
    django.db.utils.IntegrityError: UNIQUE constraint failed: libman_klass.school_id, libman_klass.name
    [09/Jun/2021 11:14:57] "GET /library/move/students HTTP/1.1" 500 125470

【问题讨论】:

    标签: python-3.x django django-views


    【解决方案1】:

    错误告诉你:django.db.utils.IntegrityError: UNIQUE constraint failed: libman_klass.school_id, libman_klass.name。这意味着您的模型上的 unique_together 在您尝试保存数据库中已存在的 school 和 name 时会引发错误。

    例如下面的代码,带有school=request.user.school 和name=2 的Klass 已经存在,但您有一个唯一的共同约束来防止这种情况发生。

    Klass.objects.filter(school=request.user.school,name=1).update(name=2)
    

    如果您不希望这样做,请删除 unique_together 约束并再次运行迁移 (./manage.py makemigrations ./manage.py migrate) 或 IntegrityError 除外:

    try:
        Klass.objects.filter(
            school=request.user.school,
            name=1
        ).update(name=2)
    except IntegrityError as e:
        # do something 
        messages.info(request,f'erroerd at {e}')
    return redirect('/')
    

    【讨论】:

    • 您需要删除模型中的 unique_together 并再次运行迁移。或者您可以排除 IntegrityError 并处理它。
    • 我已经用IntegrityError 处理更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2019-05-25
    • 2018-09-11
    相关资源
    最近更新 更多