Correct way to use get_or_create?
--
Track title: CC E Schuberts Piano Sonata D 784 in A
--
Chapters
00:00 Question
00:35 Accepted answer (Score 485)
01:21 Answer 2 (Score 41)
01:35 Answer 3 (Score 30)
01:58 Answer 4 (Score 22)
02:18 Thank you
--
Full question
https://stackoverflow.com/questions/1941...
Accepted answer links:
[get_or_create]: https://docs.djangoproject.com/en/stable...
Answer 3 links:
[get_or_create()]: https://docs.djangoproject.com/en/stable...
--
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 ofget_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