简体   繁体   English

如何更新模型中所有对象的参数-Django

[英]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.

相关问题 如何在不迭代python的情况下显式批量更新Django模型的所有对象? - How to distinctly bulk update all objects of a django model without iterating over them in python? Django:如何通过另一个模型获取与模型相关的所有对象? - Django: How to get all objects related to a model by another model? 如何在 django rest 框架中列出来自特定 model 的所有对象? - How to list all objects from particular model in django rest framework? 如何将自定义字段添加到 django 的所有对象 model - how add custom fild to all objects of django model 如何将ajax调用应用于DJANGO中的所有模型对象 - How to apply ajax call to all model objects in DJANGO 如何在Django模型ForeignKey和OneToOneField中获取所有相关对象 - How to get all related objects in django model ForeignKey and OneToOneField 如何在django中选择从另一个模型中键入外键的所有对象? - How to select all objects that are foreign keyed from another model in django? 如何对 Django 中的所有 model 对象进行反向关系查找? - How to do backward relationships lookup for all model objects in Django? 如何更新 Django 中查询集中所有对象的字段值? - How can I update the field value of all objects in a queryset in Django? Python / Django比较和更新模型对象 - Python / Django compare and update model objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM