English 中文(简体)
MongoEngine - Document Inheritance
  • 时间:2024-11-05

MongoEngine - Document Inheritance


Previous Page Next Page  

It is possible to define an inherited class of any user defined Document class. The inherited class may add extra fields if required. However, since such as a class is not a direct subclass of Document class, it will not create a new collection, instead its objects are stored in a collection used by its parent class. In the parent class, meta attribute ‘allow_inheritance the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection.

In the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection.


from mongoengine import *
con=connect( newdb )
class employee (Document):
name=StringField(required=True)
branch=StringField()
meta={ allow_inheritance :True}
class salary(employee):
dept=StringField()
sal=IntField()
e1=employee(name= Bharat , branch= Chennai ).save()
s1=salary(name= Deep , branch= Hyderabad , dept= Accounts , sal=25000).save()

We can verify that two documents are stored in employee collection as follows −


{
"_id":{"$oid":"5ebc34f44baa3752530b278a"},
"_cls":"employee",
"name":"Bharat",
"branch":"Chennai"
}
{
"_id":{"$oid":"5ebc34f44baa3752530b278b"},
"_cls":"employee.salary",
"name":"Deep",
"branch":"Hyderabad",
"dept":"Accounts",
"sal":{"$numberInt":"25000"}
}

Note that, in order to identify the respective Document class, MongoEngine adds a “_cls” field and sets its value as "employee" and "employee.salary".

If you want to provide extra functionapty to a group of Document classes, but without overhead of inheritance, you can first create an abstract class and then derive one or more classes from the same. To make a class abstract, meta attribute ‘abstract’ is set to True.


from mongoengine import *
con=connect( newdb )

class shape (Document):
   meta={ abstract :True}
   def area(self):
      pass

class rectangle(shape):
   width=IntField()
   height=IntField()
   def area(self):
      return self.width*self.height

r1=rectangle(width=20, height=30).save()
Advertisements