与仅在 django 中更新相同值更新相比,使用bulk_update 是否有任何性能优势?

Esi*_*ngs 6 django django-models django-rest-framework

我有下面的代码

Subscription.objects.filter(id__in=[subscription.id for subscription in subscriptions]).update(renewal_notification_sent=True)
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有类似的事情

updatable_subscriptions = []
subs = Subscription.objects.filter(id__in=[subscription.id for subscription in subscriptions])
for sub in subs:
    sub.renewal_notification_sent = True

updatable_subscriptions.append(
    subs
)

# then
Subscription.objects.bulk_update(updatable_subscriptions, ["renewal_notification_sent"])
Run Code Online (Sandbox Code Playgroud)

会有任何性能优势。filter调用后是否会update进行 2 次数据库查询?

小智 -2

过滤后更新进行 2 个查询。关于性能,bulk_update 使用 case 进行 sql 更新,而 update 在幕后进行简单更新,对于更大的更新,最好使用bulk_update。