stackoverfolow给出的解决方法都是看手册
for item in my_queryset: item.save()
马上升级多个objects
有时候你想要为一个QuerySet里的所有objects设置一个特定值空间。你可以用update()方法。例如:
# Update all the headlines with pub_date in 2007.
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
用这个方法,你只能设置非关联空间和ForeignKey空间。升级非关联空间,请提供一个新取值作为恒值。升级ForeignKey空间,请设置一个新值升级你关注的新model。
>>> b = Blog.objects.get(pk=1)
# Change every Entry so that it belongs to this Blog.
>>> Entry.objects.all().update(blog=b)
update()一旦使用立即生效并返回query对应的行的数字(这些数字可能并不等于那些已经拥有新值的行的数字)。被升级的QuerySet仅有的局限是它只能访问一个数据库表格——model对应的主表。你可以在相关联控件的基础上筛选,但是你只能升级这个model的主表列。例如:
>>> b = Blog.objects.get(pk=1)
# Update all the headlines belonging to this Blog.
>>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')
注意,upadate()是直接被翻译成SQL命令的。它是一系列用于直接升级的操作命令集。它并不对你的model运行save()命令,也不发出pre_save或post_save信号(这些信号是由save()命令发出的),也不会照顾到auto_now空间选项。如果你想要保存一个QuerySet的每一小项并确保每个实例都运行save()命令,你不需要任何特别的函数。你需要的是直接对其运行循环语句并且发出save()命令。
for item in my_queryset:
item.save()
Calls to update can also use F expressions
to update one field based on the value of another field in the model. This is especially useful for incrementing counters based upon their current value. For example, to increment the pingback count for every entry in the blog:
>>> Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
However, unlike F()
objects in filter and exclude clauses, you can’t introduce joins when you use F()
objects in an update – you can only reference fields local to the model being updated. If you attempt to introduce a join with an F()
object, a FieldError
will be raised:
# THIS WILL RAISE A FieldError
>>> Entry.objects.update(headline=F('blog__name'))