MongoDB - MongoEngine - How do I follow the link from the "other side"?

since four days Iโ€™m trying to figure out how to follow a link from one class to another, starting with the class it refers to. In SQL-Django, there is a related_name to achieve this ...

For example, I have this class:

 class MyClass(Document): ... other_classes = ListField(ReferenceField(Other_Class)) 

and this one:

 class Other_Class(Document): ... 

Now I want to switch from Other_Class to MyClass ... Any ideas?

Thanks,

Ron

+4
source share
3 answers

Here is an example showing how to request it:

 import unittest from mongoengine import * class StackOverFlowTest(unittest.TestCase): def setUp(self): conn = connect(db='mongoenginetest') def test_one_two_many(self): class MyClass(Document): other_classes = ListField(ReferenceField("OtherClass")) class OtherClass(Document): text = StringField() MyClass.drop_collection() OtherClass.drop_collection() o1 = OtherClass(text='one').save() o2 = OtherClass(text='two').save() m = MyClass(other_classes=[o1, o2]).save() # Lookup MyClass that has o1 in its other_classes self.assertEqual(m, MyClass.objects.get(other_classes=o1)) # Lookup MyClass where either o1 or o2 matches self.assertEqual(m, MyClass.objects.get(other_classes__in=[o1, o2])) 

The main question is: do you need to save the list of links in MyClass ? It might be more convenient to store relationships only on OtherClass ..

+3
source

While I was thinking about my problem, I came up with a solution.

I just add the identifier of my reference class to my model.

Here is an example:

 class MyClass(Document): ... other_classes = ListField(ReferenceField(Other_Class)) class Other_Class(Document): myclass = ReferenceField(MyClass) 

I'm not quite sure that this is a Mongolian way of doing this, but I'm sure it works :)

You can optionally omit the other_classes attribute in MyClass to avoid redundancy, but then you need a query like this to get the "children" objects:

 Other_Class.objects(myclass = myclass.id) 
0
source

Try this query:

 oc = Other_Class() MyClass.objects.find( other_classes__all = [oc.id] ) 
0
source

All Articles