Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to use get_or_create?

Tags:

python

django

I'm trying to use get_or_create for some fields in my forms, but I'm getting a 500 error when I try to do so.

One of the lines looks like this:

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

The error I get for the above code is:

Cannot assign "(<Source: Website>, False)": "Customer.source"     must be a "Source" instance. 
like image 481
Stephen Avatar asked Dec 21 '09 16:12

Stephen


People also ask

What does 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 is Get_or_create?

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.


2 Answers

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. >>> created False 

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") 
like image 167
Astra Avatar answered Sep 23 '22 00:09

Astra


get_or_create returns a tuple.

customer.source, created = Source.objects.get_or_create(name="Website") 
like image 43
Tobu Avatar answered Sep 23 '22 00:09

Tobu