The Python Oracle

Correct way to use get_or_create?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence

--

Chapters
00:00 Correct Way To Use Get_or_create?
00:25 Answer 1 Score 44
00:35 Accepted Answer Score 523
01:14 Answer 3 Score 7
01:45 Answer 4 Score 33
02:03 Thank you

--

Full question
https://stackoverflow.com/questions/1941...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django

#avk47



ACCEPTED ANSWER

Score 523


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")



ANSWER 2

Score 44


get_or_create returns a tuple.

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



ANSWER 3

Score 33


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.




ANSWER 4

Score 7


The issue you are encountering is a documented feature of get_or_create.

When using keyword arguments other than "defaults" the return value of get_or_create is an instance. That's why it is showing you the parens in the return value.

you could use customer.source = Source.objects.get_or_create(name="Website")[0] to get the correct value.

Here is a link for the documentation: http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs