更新选择的对象,每个对象具有不同的批量值(Django) [英] Updating selection of objects, each with a different value in bulk (Django)
问题描述
想象一下,我有一个python字典,其中的键是现有的用户ID,而值是要添加到这些用户的现有分数中的分数。
Imagine I have a python dictionary where keys are existing user ids, and values are scores to be added to those users' existing scores.
例如: {1:1580,4:540,2:2:678}
(这可能会扩展为 n
k,v对)
For example: {1: 1580, 4: 540, 2: 678}
(this could stretch to n
k,v pairs)
我需要更新所有这些用户对象的分数(updated_score = original_score + new_score )。一种迭代的方式是这样的,例如:
I need to update the scores of all these user objects (updated_score = original_score + new_score). One way to do it is iteratively, like so:
from django.db.models import F
scores = {1: 1580, 4: 540, 2: 678}
for user_id,score_to_add in scores.iteritems():
UserProfile.objects.filter(user_id=user_id).update(score=F('score')+score_to_add)
但这是多个数据库调用。我可以一次通话吗?一个说明性的例子将是很好的。如您所料,这是针对Django项目的。
But that's multiple DB calls. Can I do it in a single call? An illustrative example would be great. As you would have guessed, this is for a Django project.
推荐答案
类似的东西:
from django.db.models import F
from django.db import transaction
with transaction.atomic():
scores = {1: 1580, 4: 540, 2: 678}
for user_id,score_to_add in scores:
UserProfile.objects.filter(user_id=user_id).update(score=F('score')+score_to_add)
有关此此处
您可以查看这个答案也是。
[更新] :
TL; DR:它不会不执行一个数据库查询,但由于每个查询都没有数据库开销,因此速度会更快。
TL;DR: It'll not make one db query but it will be faster cause each query lacks the database overhead.
作为文档和@ahmed在他的答案说:
As the docs and @ahmed in his answer say:
Django的默认行为是在自动提交模式。除非事务
处于活动状态,否则每个查询都会立即提交给数据库
。
Django’s default behavior is to run in autocommit mode. Each query is immediately committed to the database, unless a transaction is active.
通过将与transaction.atomic一起使用。 ()
所有插入都分组为
单笔交易。提交事务所需的时间在所有封闭的插入语句中摊销了
,因此每个
插入语句的时间都大大减少了。
By using with transaction.atomic()
all the inserts are grouped into a
single transaction. The time needed to commit the transaction is
amortized over all the enclosed insert statements and so the time per
insert statement is greatly reduced.
这篇关于更新选择的对象,每个对象具有不同的批量值(Django)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!