Question

I've been using the get_or_create method with MongoEngine in a Django app. Today, I noticed there were a few duplicate entries. I came across this in the MongoEngine API Reference for get_or_create:

This requires two separate operations and therefore a race condition exists. Because there are no transactions in mongoDB other approaches should be investigated, to ensure you don’t accidentally duplicate data when using this method. This is now scheduled to be removed before 1.0

Should I be using something like this?:

from models import Post
post = Post(name='hello')
try:
    Posts.objects.get(name=post.name)
    print "exists"
except:
    post.save()
    print "saved"

Will that solve my problem? Is there a better way?

Était-ce utile?

La solution

To perform an upsert use the following syntax:

Posts.objects(name="hello").update(set__X=Y, upsert=True)

That will add a post with the name "hello" and where X = Y if it doesn't already exist, otherwise it will update an existing post just setting X = Y.

Autres conseils

If you need pass a dictionery, can do this:

post = Post.objects(name="hello").first() or Post(name="hello")

then you can update with something like this:

# data = dictionary_with_data
for field, value in data.items():
    post[field] = value

post.save()
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top