Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A get_or_create replacement #1157

Closed
BeardedSteve opened this issue Nov 13, 2015 · 1 comment
Closed

A get_or_create replacement #1157

BeardedSteve opened this issue Nov 13, 2015 · 1 comment

Comments

@BeardedSteve
Copy link

So #300 has been done, get_or_create has gone, good riddance.

The behaviour is still very useful and can be achieved with an upsert. However, whereas get_or_create returned a document, update_one with full_result=True returns a dict with some info about the result of the operation.

This has led me to write something like this a few times:

query = Hooman.objects(name="Charlie", job="Winning")
man_update = query.update_one(name="Charlie", job="Winning", upsert=True, full_result=True)
if man_update['updatedExisting']:
    da_man = query.get()
else:
    da_man = Hooman.objects.with_id(man_update['upserted'])

Three questions:

  1. Is this the best way to do this?
  2. If it is the best way (or the best way is similar number of keystrokes) can the above code be generalised to method somewhere in mongoengine?
  3. If it can be included, where might be the best place?

My proposed answers:

  1. Probably not but close enough
  2. Yes that would be nice
  3. Add an upsert_one method on BaseQuerySet (Upsert one #1167)

Appreciate any thoughts.

EDIT: For anyone finding this in future I changed point 3 above to match the accepted PR #1167

@decklord
Copy link

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants