Django ORM 批量更新

发布于 2025-01-16 17:12:03 字数 699 浏览 2 评论 0原文

我一直坚持这个任务。 我有教授模型,我需要更新 2 个查询,但我的数据库中有 6 个查询。

from django.db import models

class Professor(models.Model):
   first_name = models.CharField(max_length=30)
   last_name = models.CharField(max_length=30)
   age = models.IntegerField(default=18)

我的职能。

def update_professor_first_names():
    first_name_updates = [(1, 'freddie'), (2, 'mady'), (3, 'hady'), (4, 'michael'), (5, 'rose')]
    tmp = []
    for prof_id, new_first_name in first_name_updates:
        prof = Professor.objects.get(id=prof_id)
        prof.first_name = new_first_name
        tmp.append(prof)
    Professor.objects.bulk_update(tmp, ['first_name'])

请给我一些建议。

I have stuck on this task.
I have Professor model and i need to update from 2 queries but i have 6 queries in my DB.

from django.db import models

class Professor(models.Model):
   first_name = models.CharField(max_length=30)
   last_name = models.CharField(max_length=30)
   age = models.IntegerField(default=18)

My function.

def update_professor_first_names():
    first_name_updates = [(1, 'freddie'), (2, 'mady'), (3, 'hady'), (4, 'michael'), (5, 'rose')]
    tmp = []
    for prof_id, new_first_name in first_name_updates:
        prof = Professor.objects.get(id=prof_id)
        prof.first_name = new_first_name
        tmp.append(prof)
    Professor.objects.bulk_update(tmp, ['first_name'])

Please give me some advices.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸵鸟症 2025-01-23 17:12:03

现在,您正在对每个 ID 运行 get,这会生成 5 个查询,然后运行一个更新查询,总共 6 个查询。

您可以使用 __in 运算符与所有 ID 一起运行一个查询来获取您想要更新的教授,然后在分配名称后运行批量更新,总共两个查询:

id_set = [id for id, first_name in first_name_updates]
profs_to_update = Professor.objects.filter(id__in=id_set)

for prof in profs_to_update:
    prof.first_name = next(first_name for id, first_name in first_name_updates if id == prof.id)

Professor.objects.bulk_update(profs_to_update, ['first_name'])

right now you're running a get on every ID which generates 5 queries, then one for the update, which totals 6 queries.

you can use the __in operator with all of the IDs to run one query getting the professors you want to update, then run the bulk update after you've assigned the names, for two queries total:

id_set = [id for id, first_name in first_name_updates]
profs_to_update = Professor.objects.filter(id__in=id_set)

for prof in profs_to_update:
    prof.first_name = next(first_name for id, first_name in first_name_updates if id == prof.id)

Professor.objects.bulk_update(profs_to_update, ['first_name'])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文