[英]How to change a field of all objects in a django queryset to a value but I don't want to save it
I have two models Question
and Choice
.我有两个模型
Question
和Choice
。
Here I want to change the value of all choice.vote to 0
.在这里,我想将所有
choice.vote to 0
的值更改choice.vote to 0
。 But I don't want to update it.但我不想更新它。
I know I can update the field by calling query_set.update(field=value)
.我知道我可以通过调用
query_set.update(field=value)
来更新该字段。
Extra requirements:额外要求:
Any help will be appreciated.任何帮助将不胜感激。
updated_choice_list = []
for question in Question.objects.filter(some_condition):
for choice in question.choice_set.all():
choice.vote = 0 # I dont want to save the choice vote
updated_choice_list.append(choice)
According to the details you've given this should do it.根据您提供的详细信息,应该这样做。
choices = [c for c in Choice.objects.filter(question__some_filter=something).all()]
for c in choices:
c.vote = 0
Your current code doesn't change anything in the database, so that is done.您当前的代码不会更改数据库中的任何内容,因此已完成。 Depending on your
some_condition
you can remove the nested for loops, by querying the Choices directly:根据您的
some_condition
您可以通过直接查询 Choices 来删除嵌套的 for 循环:
updated_choice_list = Choice.objects.filter(question__some_condition):
for choice in updated_choice_list:
choice.vote = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.