Skip to content

Instantly share code, notes, and snippets.

@mgilangjanuar
Created March 18, 2018 18:17
Show Gist options
  • Save mgilangjanuar/7f79838099ea6492d6d0193796a471de to your computer and use it in GitHub Desktop.
Save mgilangjanuar/7f79838099ea6492d6d0193796a471de to your computer and use it in GitHub Desktop.
Find documents in mongoengine with dict object
from mongoengine.queryset.visitor import Q
class Query():
def _parse(queries):
this = Query()
this._or = queries.get('or', [])
this._and = queries.get('and', [])
attr = next(iter(queries))
this.q = Q()
this.q.query = {attr: queries[attr]}
return this
def execute(query):
query = Query._parse(query)
if (not query._or and not query._and):
return query.q
result = query.q
if (query._and):
for q in query._and:
result = result & Query.execute(q)
if (query._or):
for q in query._or:
result = result | Query.execute(q)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment