I was wondering what exactly is the difference between retrieving entries and then bulk updating in Django vs creating an array of the model objects and pushing it to bulk_update
.
NOTE:
- The entries with the given
name
are unique and always exist in the database.
models.py
from django.db import models
class Subject(models.Model):
name = models.CharField(max_length=30, unique=True)
credits = models.FloatField()
The updating entries logic:
update_logic.py
from my_app.models import Subjects
def update_credits_without_lookup(subjects):
"""
This method will update credits without getting a resultset from the DB.
eg: subjects = [
{"name":"Physics","credits":10},
{"name":"Chemistry","credits":10},
{"name":"Mathematics","credits":10},
{"name":"English","credits":5}
]
"""
subject_objects = [Subject(name=subject["name"], credits=subject["credits"]) for subject in subjects]
Subject.objects.bulk_update(subject_objects, ['credits'])
def update_credits_with_lookup(subjects):
"""
This method will update credits by first looking up in the DB.
eg: subjects = [
{"name":"Physics","credits":10},
{"name":"Chemistry","credits":10},
{"name":"Mathematics","credits":10},
{"name":"English","credits":5}
]
"""
subject_entries = Subject.objects.filter(
name__in=[[subject["name"] for subject in subjects]])
# I can make this better by ignoring/creating subjects that might have no resultset in the DB.
# Please consider that the subjects passed are always there in the DB.
for subject_entry, subject in zip(subject_entries, subjects):
subject_entry.credits = subject["credits"]
Subject.objects.bulk_update(subject_entries, ['credits'])
Considering my NOTE
is it advised to use the update_credits_without_lookup
method, since it will save an extra lookup in the DB and the bulk_update query will anyway ignore entries which don't exist in the DB. And if I were to use update_credits_with_lookup
method is there a more efficient way to do it?
question from:
https://stackoverflow.com/questions/65869632/django-queryset-bulk-update-with-and-without-lookup 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…