'Django ORM bulk_update

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.



Solution 1:[1]

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'])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1