简体   繁体   English

如何将 django 查询集中所有对象的字段更改为一个值但我不想保存它

[英]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 .我有两个模型QuestionChoice

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:额外要求:

  • I don't want to affect anything to my database我不想对我的数据库产生任何影响
  • also, more importantly, I want to avoid this nested for loop .此外,更重要的是,我想避免这种嵌套的 for 循环

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM