I have used the get_or_create
function on my models in Django. This function returns two values. One is the object itself and the other a boolean flag that indicates whether an existing object was retrieved or a new one created.
Normally, a function can return a single value or a collection of values like a tuple
, list
or a dictionary.
How does a function like get_or_create
return two values?
The trick with the get_or_create method is that it actually returns a tuple of (object, created) . The first element is an instance of the model you are trying to retrieve and the second is a boolean flag to tell if the instance was created or not.
Django get_or_create returns the object that it got and a boolean value that specifies whether the object was created or not. If get_or_create finds multiple objects it will raise a MultipleObjectsReturned exception.
_set is associated with reverse relation on a model. Django allows you to access reverse relations on a model. By default, Django creates a manager ( RelatedManager ) on your model to handle this, named <model>_set, where <model> is your model name in lowercase.
It would return the object of your model on which you are querying. If nothing matches and no rows is returned, it would through a Model.
get_or_create()
simply returns a tuple of the two values. You can then use sequence unpacking to bind the two tuple entries to two names, like in the documentation example:
p, created = Person.objects.get_or_create(
first_name='John', last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With