Django ORM 批量更新
我一直坚持这个任务。 我有教授模型,我需要更新 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
现在,您正在对每个 ID 运行
get
,这会生成 5 个查询,然后运行一个更新查询,总共 6 个查询。您可以使用 __in 运算符与所有 ID 一起运行一个查询来获取您想要更新的教授,然后在分配名称后运行批量更新,总共两个查询:
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: