Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model method - create_or_update

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.

like image 824
snakesNbronies Avatar asked May 02 '13 03:05

snakesNbronies


People also ask

What is the purpose of __ Str__ method in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model. # Create your models here. This will display the objects as something always in the admin interface.

How do I create an instance of a Django model?

To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .

How Django knows to update VS insert?

The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.


1 Answers

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' 
like image 65
suhailvs Avatar answered Sep 28 '22 10:09

suhailvs