Django model method - create_or_update

71,883

Solution 1

See QuerySet.update_or_create (new in Django 1.7dev)

Solution 2

There is update_or_create, eg::

obj, created = Person.objects.update_or_create(
    first_name='John', last_name='Lennon',
    defaults={'first_name': 'Bob'},
)
# If person exists with first_name='John' & last_name='Lennon' then update first_name='Bob'
# Else create new person with first_name='Bob' & last_name='Lennon'
Share:
71,883
snakesNbronies
Author by

snakesNbronies

Don't be a dick. - Wheaton's Rule

Updated on July 09, 2022

Comments

  • snakesNbronies
    snakesNbronies almost 2 years

    Similar to get_or_create, I would like to be able to update_or_create in Django.

    Until now, I have using an approaching similar to how @Daniel Roseman does it here. However, I'd like to do this more succinctly as a model method.

    This snippet is quite old and I was wondering if there is a better way to do this in more recent version of Django.

  • Shahriar Rahman Zahin
    Shahriar Rahman Zahin over 2 years
    Thanks for explaining what the defaults does. It's super confusing in docs. :D
  • suhailvs
    suhailvs over 2 years
    @ShahriarRahmanZahin thank you for the kind words. maybe i will submit a pull request in django\
  • Shahriar Rahman Zahin
    Shahriar Rahman Zahin over 2 years
    That will be fantastic! @suhailvs
  • Seb
    Seb about 2 years
    Best explanation I've seen so far about what the defaults does. Not clear in the documentation.