Correct way to use get_or_create? Correct way to use get_or_create? python python

Correct way to use get_or_create?


From the documentation get_or_create:

# get_or_create() a person with similar first names.p, created = Person.objects.get_or_create(    first_name='John',    last_name='Lennon',    defaults={'birthday': date(1940, 10, 9)},)# get_or_create() didn't have to create an object.>>> createdFalse

Explanation: Fields to be evaluated for similarity, have to be mentioned outside defaults. Rest of the fields have to be included in defaults. In case CREATE event occurs, all the fields are taken into consideration.

It looks like you need to be returning into a tuple, instead of a single variable, do like this:

customer.source,created = Source.objects.get_or_create(name="Website")


get_or_create returns a tuple.

customer.source, created = Source.objects.get_or_create(name="Website")


get_or_create() returns a tuple:

customer.source, created  = Source.objects.get_or_create(name="Website")
  • created has a boolean value, is created or not.

  • customer.source has an object of get_or_create() method.