5

我想像这样更新 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)
4

2 回答 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

于 2013-08-05T07:35:10.570 回答
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是 dict,您可以尝试使用它而不是 data_dict 但确保键与您在 DB 中的字段名称匹配。

这里讨论了另一种方法:如何更新 django 模型实例的多个字段?但它看起来有点hacky。

于 2013-08-05T07:37:11.473 回答