I understand that get_or_create
is now deprecated in favour of using upsert
, but how do I make update_one
to return the object rather the number of objects modified, and can I just retrieve an object if I don't want to update anything?
e.g.
Model.objects.get_or_create(first_name='John', last_name='Potter', age=40)
# assuming that first_name + last_name + age are enough to uniquiely indentify a person
returns a Model object (a new object if it didn't exist, and existing object if it does). What would be the equivalent of this using the new method?
Model.objects(first_name='John', last_name='Potter', age=40).update_one(upsert=True)
# returns number of objects (1)
Model.objects(first_name='John', last_name='Potter', age=40).update_one(set__first_name='John', set__last_name='Potter', set__age=40,upsert=True)
# returns number of objects (1)
Is there a way to make it return the object, and make it behave exactly like get_or_create
?
I couldn't find how to do this in the documentation
You should look at
modify
. Passing anew=True
you'll get the updated object (or document, in mongodb parlance).You are very close but you need to use a findAndModify command via modify rather than an update command.
Take note of the first 2 modify kwargs -
upsert
andnew
. Also take note of the $setOnInsert operator example which will only set a field if the findAndModify does an upsert.