[Django]-Django update_or_create is updating even if there is no change?

6đź‘Ť

âś…

from the docs:

The update_or_create method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in the defaults dictionary.

This is meant as a shortcut to boilerplatish code. For example:

defaults = {'first_name': 'Bob'}
try:
    obj = Person.objects.get(first_name='John', last_name='Lennon')
    for key, value in defaults.items():
        setattr(obj, key, value)
    obj.save()
except Person.DoesNotExist:
    new_values = {'first_name': 'John', 'last_name': 'Lennon'}
    new_values.update(defaults)
    obj = Person(**new_values)
    obj.save()

the sample code describes what exactly the update_or_create does.

1đź‘Ť

No, you’ve just used first_name='jule' as a filter to get the db entry. That only will check and will not do any update since you are not using defaults dict in the call.

More info https://docs.djangoproject.com/en/3.0/ref/models/querysets/#update-or-create

Some more info about the case when it is created.

https://github.com/django/django/blob/d6505273cd889886caca57884fa79941b18c2ea6/django/db/models/query.py#L576

It doesn’t do any update if the object didn’t exist. Just creates it.
You don’t have to put defaults={'first_name': 'jule'} into the method since it is done by Django “under the hood”.

defaults dict is a dict with extra changes, using defaults you can “rename” your user I believe by passing a new name, but don’t need to pass the same params there 🙂

Leave a comment