Does get_or_create() have to save right away? (Django)
Question:
I need to use something like get_or_create() but the problem is that I have a lot of fields and I don’t want to set defaults (which don’t make sense anyway), and if I don’t set defaults it returns an error, because it saves the object right away apparently.
I can set the fields to null=True, but I don’t want null fields.
Is there any other method or any extra parameter that can be sent to get_or_create() so that it instantiates an object but doesn’t save it until I call save() on it?
Thanks.
Answers:
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.
I need to use something like get_or_create() but the problem is that I have a lot of fields and I don’t want to set defaults (which don’t make sense anyway), and if I don’t set defaults it returns an error, because it saves the object right away apparently.
I can set the fields to null=True, but I don’t want null fields.
Is there any other method or any extra parameter that can be sent to get_or_create() so that it instantiates an object but doesn’t save it until I call save() on it?
Thanks.
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.