Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the get_or_create function in Django return two values?

Tags:

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?

like image 455
tomrs Avatar asked Jan 16 '11 16:01

tomrs


People also ask

What does Django Get_or_create return?

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.

What does Get_or_create do in Django?

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.

What is _SET all () in Django?

_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.

What does Django objects get return?

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.


1 Answers

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)})
like image 106
Sven Marnach Avatar answered Oct 16 '22 14:10

Sven Marnach