Last active
February 20, 2017 05:32
-
-
Save ikonst/10caeda3aec78646309a32135a0bc24f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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