Skip to content

Instantly share code, notes, and snippets.

@ikonst
Last active February 20, 2017 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikonst/10caeda3aec78646309a32135a0bc24f to your computer and use it in GitHub Desktop.
Save ikonst/10caeda3aec78646309a32135a0bc24f to your computer and use it in GitHub Desktop.
from mongoengine import Document, EmbeddedDocument, Q, ReferenceField
from pymongo.read_preferences import ReadPreference
all_models = Document.__subclasses__()
def referencing_models(document):
for model in all_models:
if issubclass(model, EmbeddedDocument):
continue
fields = [field for field in get_reference_fields_of_model(model)
if field.document_type == type(document)]
if fields:
yield (model, fields)
def get_referencing_documents(document):
for model, fields in referencing_models(document):
query = None
for field in fields:
params = {field.name: document.id}
subquery = Q(**params)
if query:
query |= subquery
else:
query = subquery
objects = (model
.objects(subquery, read_preference=ReadPreference.SECONDARY_ONLY)
.no_dereference()
.no_cache())
for ref_doc in objects:
yield ref_doc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment