Search code examples
pythonmongodbflask-mongoengine

what is correct way to define Many2Many, Many2One in mongoengine


I am creating a data model for my new project where I have to use Many2Many, Many2One, One2Many reference using flask-mongoengine. Can someone describe how to define Many2Many and other reference field using mongoengine?


Solution

  • The following are the most common ways to do it:

    1) 1-to-many with a simple ReferenceField

    class Client(Document):
        name = StringField()
    
        @property
        def account(self):
              return Account.objects(client=self).get()  
    
    class Account(Document):
        client = ReferenceField(Client)
    
    bob = Client(name='Bob').save()
    acc1 = Account(client=bob).save()
    acc2 = Account(client=bob).save()
    

    2) Many-2-Many with a list(ReferenceField)

    class Client(Document):
        name = StringField()
    
        @property
        def accounts(self):
              return Account.objects(client=self)  
    
    class M2MAccount(Document):
        clients = ListField(ReferenceField(Client))
    
    bob = Client(name='Bob').save()
    john = Client(name='John').save()
    m2m_acc = M2MAccount(clients=[bob, john]).save()
    

    Note that the @property is optional, its just for convenience