[Django]-Django save or update model

3👍

get_or_create provides a way of getting or creating. Not saving or updating. Its idea is: I want to get a model, and if it doesn’t exist, I want to create it and get it.

In Django, you don’t have to worry about getting the name or the surname or any attribute. You get an instance of the model which has all the attributes, I.e.

instance = Model.objects.get(name='firstName',surname='lastName')

print instance.birthday
print instance.name
print instance.surname

An overview of the idea could be: a Model is a data structure with a set of attributes, an instance is a particular instance of a model (uniquely identified by a primary_key (pk), a number) which has a specific set of attributes (e.g. name="firstName").

Model.objects.get is used to go to the database and retrieve a specific instance with a specific attribute or set of attributes.

2👍

Since Django 1.7 there’s update_or_create:

obj, created = Person.objects.update_or_create(
    first_name='John',
    last_name='Lennon',
    defaults=updated_values
)

The parameters you give are the ones that will be used to find an existing object, the defaults are the parameters that will be updated on that existing or newly created object.

A tuple is returned, obj is the created or updated object and created is a boolean specifying whether a new object was created.

Docs: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update-or-create

Leave a comment