简体   繁体   English

Django queryset update() 以 += 方式

[英]Django queryset update() in += way

How can I call update on Django queryset, that does not write particular value, but modify the value already there, as follows如何在 Django 查询集上调用更新,它不写入特定值,而是修改已经存在的值,如下所示

Entry.objects.filter(pub_date__year=2010).update(count+=1)

How can I achieve that?我怎样才能做到这一点?

You can use F expression from docs:您可以使用文档中的F 表达式

reporter = Reporters.objects.filter(name='Tintin')记者 = Reporters.objects.filter(name='Tintin')

reporter.update(stories_filed=F('stories_filed') + 1)记者.更新(stories_filed = F('stories_filed')+ 1)

Try this:尝试这个:

from django.db.models import F
Entry.objects.filter(pub_date__year=2010).update(count=F('count') + 1)
for e in Entry.objects.filter(pub_date__year=2010):
    e.count+= 1
    e.save()

Pay attention to:注意:

if you are using F-expression - you are using .update() method.如果您正在使用 F 表达式 - 您正在使用.update()方法。

If you have a needed logic in the overridden .save() method - it won't be called in such updating.如果您在重写的.save()方法中有所需的逻辑 - 在此类更新中不会调用它。

To use the .save() method you need to use a general approach:要使用.save()方法,您需要使用通用方法:

foo.bar += 1
foo.save()

Docs : 文档

Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on your models, nor does it emit the pre_save or post_save signals (which are a consequence of calling Model.save()最后,要意识到 update() 在 SQL 级别执行更新,因此不会在您的模型上调用任何 save() 方法,也不会发出 pre_save 或 post_save 信号(这是调用 Model.save( )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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