Sunday, February 28, 2021

save() in a loop. (Data Migrations example).


I'm wondering about this code snippet from the documentation

for person in Person.objects.all():
    person.name = '%s %s' % (person.first_name, person.last_name)
    person.save()

This looks like the N+1 Query problem but maybe I'm wrong. I usually avoid this kind of code in my projects.
How many times does this hit the database?
Does the fact that it's in a migration (therefore a transaction) change anything?

Perhaps, the better way would be to do

Person.objects.update(name=Concat(F('first_name'), Value(' '), F('last_name')))

What's the correct way?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ab38497b-be1d-42a7-bbcf-75055dd95856n%40googlegroups.com.

No comments:

Post a Comment