The Python Oracle

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

--------------------------------------------------
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: Cosmic Puzzle

--

Chapters
00:00 Does Get_or_create() Have To Save Right Away? (Django)
00:41 Accepted Answer Score 39
00:55 Thank you

--

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

--

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.