07 Document Relationship Many To Many

from mongoengine import *
connect('RelationExample')

Create Document Class

class Book(Document):
    title = StringField()
    pages = IntField()
    price = DecimalField()
    authors = ListField(ReferenceField('Author')) 
    
class Author(Document):    
    name=StringField()
    email=EmailField()
    books = ListField(ReferenceField(Book))   
author1=Author(name='olee',email='olee.techs@gmail.com')
author2=Author(name='Mim',email='mim.techs@gmail.com')
author1.save()
author2.save()
book1 = Book(title='Python Basic',pages=200,price=250.0)
book2 = Book(title='Python OOP',pages=250,price=265.0)
book1.save()
book2.save()
book1.authors=[author1,author2]
book1.save()
for book in author1.books:
    print(book.title)
print(book1.authors[0].name)
print(author1.books[0].title)

Last updated