The Python Oracle

Does get_or_create() have to save right away? (Django)

This video explains
Does get_or_create() have to save right away? (Django)

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3

--

Chapters
00:00 Question
00:49 Accepted answer (Score 39)
01:09 Thank you

--

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

Accepted answer links:
[get_or_create]: https://github.com/django/django/blob/ma...

--

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

--

Tags
#python #django #djangomodels #djangoorm

#avk47



ACCEPTED ANSWER

Score 39


You can just do:

try:
    obj = Model.objects.get(**kwargs)
except Model.DoesNotExist:
    obj = Model(**dict((k,v) for (k,v) in kwargs.items() if '__' not in k))

which is pretty much what get_or_create does, sans commit.