在Django中如何更新查询集(queryset)?

4
我想要像下面这样更新Django模型中的数据:

 video_id = request.POST['video_id']
     # Get the form data and update the data

 video = VideoInfoForm(request.POST)

 VideoInfo.objects.filter(id=video_id).update(video)

  return HttpResponseRedirect('/main/')

新数据由用户在表单中提供。我想使用id=video_id更新数据。这会导致以下错误:
update() takes exactly 1 argument (2 given)
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  25.                 return view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
  86.         return handler(request, *args, **kwargs)
File "/home/zurelsoft/virtualenv/videoManagement/VideoManagementSystem/video/views.py" in post
  126.          VideoInfo.objects.filter(id=video_id).update(video)

Exception Type: TypeError at /updateVideo/
Exception Value: update() takes exactly 1 argument (2 given)

你想要更新什么内容? - Hieu Nguyen
1
请查看此链接:https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once - lazy functor
更新记录,其中 id=video_id。 - pynovice
我想要更新所有的字段。 - pynovice
2个回答

13
update 函数只接受关键字参数,不接受通用参数,因此你会收到 update() takes exactly 1 argument (2 given) 的错误消息。

尝试:

VideoInfo.objects.filter(id=video_id).update(foo=video)

您的模型位置在哪里:

class Video(models.Model):
    ...

class VideoInfo(models.Model):
    foo = models.ForeignKey(Video)
    ...

注意:懒惰的函数在评论中提供的文档显示了update函数的签名。


3
当然,你不能将表单实例传递给update(),因为它只接受一个参数。如果想要更新一个字段,请阅读这里的更多信息。
VideoInfo.objects.filter(id=video_id).update(video_name=request.POST['video_name'])

似乎没有官方的方法可以一次性更新多个字段,但你可以尝试这种方法:

data_dict = {'video_name': 'Test name', 'video_description': 'Something'}

VideoInfo.objects.filter(id=video_id).update(**data_dict)

由于request.POST是一个字典,您可以尝试使用它来替代data_dict,但请确保键与DB中的字段名称匹配。

另一种方法已在此处讨论:如何更新Django模型实例的多个字段?但看起来有点hacky。


直接在SQL查询中使用来自requests.POST的值而没有任何验证或净化是在寻求麻烦。 - kravietz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接