Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

python - Django queryset bulk_update with and without lookup

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:

  1. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...