在以下情况下更新Django中的queryset?
我想更新Django模型中的数据,如下所示:在以下情况下更新Django中的queryset?,django,sql-update,django-queryset,Django,Sql Update,Django Queryset,我想更新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/') 新数据由用户以表单形式
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\u 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)
update
函数只接受关键字参数,不接受一般参数,这就是为什么update()只接受1个参数(给定2个)
错误消息的原因
尝试:
您的模型所在的位置:
class Video(models.Model):
...
class VideoInfo(models.Model):
foo = models.ForeignKey(Video)
...
请注意,lazy functor的linked in comment显示了
update
函数的签名。当然不能将表单实例传递给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\u dict,但请确保键与您在DB中的字段名匹配
这里讨论了另一种方法:但它看起来有点粗糙。您到底想更新什么?检查此更新记录,其中id=video_idI我想更新所有字段。在SQL查询中直接使用requsts.POST中的值,而不进行任何验证或清理,这会带来麻烦。
data_dict = {'video_name': 'Test name', 'video_description': 'Something'}
VideoInfo.objects.filter(id=video_id).update(**data_dict)