[英]How to update parameter of all objects in a model - Django
I want to update a parameter in a Django model for all objects in the DB. 我想为数据库中的所有对象更新Django模型中的参数。 The values will be different for each object, and I'm trying to work out whether I can do this as a batch update, or whether I have to iterate through each item and save each one separately. 每个对象的值都将不同,并且我正在尝试确定是否可以将其作为批处理更新来执行,或者是否必须遍历每个项目并分别保存每个项目。
The model I'm using is an extension of the Django auth user model: 我使用的模型是Django auth用户模型的扩展:
from django.contrib.auth.models import User
from django.db import models
class Profile(models.Model):
user = models.OneToOneField(User)
position = models.PositiveIntegerField(null=False, default=0)
If I get all objects as follows: 如果我得到所有对象,如下所示:
queryset = User.objects.all()
then loop through these and update position
: 然后遍历这些并更新position
:
for user in queryset:
user.position = #SOME FUNCTION
do I have to do user.save()
within the for
loop? 我必须在for
循环中执行user.save()
吗? Or can I update each item and then save all at once to the DB? 还是可以更新每个项目,然后一次将其保存到数据库?
Django doesn't have a bulk update but what you can do is use an atomic transaction to improve performance by committing all update statements once. Django没有批量更新,但是您可以做的是使用原子事务通过一次提交所有更新语句来提高性能。
from django.db import transaction
with transaction.atomic():
for user in queryset:
user.position = #SOME FUNCTION
user.save()
There will still be len(queryset)
inserts but they will be grouped into a single transaction. 仍然会有len(queryset)
插入,但它们将被分组为一个事务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.