在Djang中批量更新(使用唯一值)的方法

2024-09-30 20:37:15 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个包含电子邮件和生日的口述:

p = [\
    {'email': 'someone@somewhere.com', 'birthday': '1990-01-01'},
    {'email': 'someone_else@somewhereelse.com', 'birthday': '1980-02-05'},
    #...etc
]

我想更新数据库中的People对象。原始sql的查询数通常与len(p)一样多,因此我考虑这样做:

^{pr2}$

我在Django没有足够的经验,不知道这是否是一个好的做法。什么是最具Python式的表达方式?在


Tags: 对象com数据库sqllen电子邮件emailetc
2条回答

过滤和更新时,相同的更新将应用于所有筛选的条目。Django不提供批量更新操作,您可以在不同的条目上更新不同的值。在

通过在transaction.atomic()块中包含for循环,而不是为for循环中的每个条目使用原子块,可以使代码更好:

with transaction.atomic():
    for person in p:
        try:              
            People.objects.filter(email=person['email']).update(birthday=person['birthday'])
        except IntegrityError:
            #handle the exception

有一个库:django-bulk-update。在

people = Person.objects.all()
for person in people:
  person.name = random.choice(random_names)

bulk_update(people, update_fields=['name']) 
# or 
Person.objects.bulk_update(people, update_fields=['name']) 

相关问题 更多 >