Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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.

like image 434
rick Avatar asked Jul 08 '09 01:07

rick


People also ask

What does Get_or_create return Django?

Django get_or_create returns the object that it got and a boolean value that specifies whether the object was created or not. If get_or_create finds multiple objects it will raise a MultipleObjectsReturned exception.

Does Django objects create call save?

Creating objectsTo create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.


1 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.

like image 195
Noah Medling Avatar answered Sep 20 '22 02:09

Noah Medling