更新对象的选择,每个对象具有不同的批量值(Django)

Updating selection of objects, each with a different value in bulk (Django)

假设我有一个 python 字典,其中键是现有用户 ID,值是要添加到这些用户现有分数的分数。

例如:{1: 1580, 4: 540, 2: 678}(这可以延伸到 n k,v 对)

我需要更新所有这些用户对象的分数 (updated_score = original_score + new_score)。一种方法是迭代,如下所示:

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 项目的。

类似的东西:

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)

关于此的更多信息here

你也可以看看

[更新]:

TL;DR:它不会进行一个数据库查询,但它会更快,因为每个查询都没有数据库开销。

正如 中的文档和@ahmed 所说:

Django’s default behavior is to run in autocommit mode. Each query is immediately committed to the database, unless a transaction is active.

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.

@nik_m提出的

transaction.atomic()是个好主意,但你也应该在单个请求中从数据库中获取记录。

from django.db.models import F
from django.db import transaction

with transaction.atomic():
    scores = {1: 1580, 4: 540, 2: 678}
    users_to_update = UserProfile.objects.filter(
        user_id__in=scores.keys()
    ) 
    for user in users_to_update:
        user.update(score=F('score') + scores[user.user_id])