Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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):
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 = {}
subquery = Q(**params)
if query:
query |= subquery
query = subquery
objects = (model
.objects(subquery, read_preference=ReadPreference.SECONDARY_ONLY)
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