Django, MongoEngine : Model Inheritance


I have recently tested Django with MongoDB, using MongoEngine to connect Django to MongoDB.

I often use some attributes common to multiple models and I do not like to copy-paste, so I always use class inheritance. This is particularly true with ORM (such as doctrine within Symfony 2 PHP Framework).

For example, my “base document” looks like (no syntax at all)

class BaseDocument
  - attribute 1
  - attribute 2
  - attribute 3

and derived documents look like

class Derived1 derived from BaseDocument
  [...]

With MongoEngine, your models derived from “Document”. For example:

from mongoengine import *

class BaseDocument(Document):
    title = StringField()
    content = StringField()  

If you want to derived from BaseDocument, there are 2 approaches:

  1. use “allow_inheritance” meta : in that case, all your data are put in the sqme collection (here, base_document) and mongoengine discriminates them by introducing a “cls” field. See MongoEngine Tutorial for an example
  2. use python class inheritance
    if you use the following example

    class Derived1(BaseDocument):
        author = StringField()
    

    you’ll get an error. MongoEngine Document is not extended properly.

So far, the best way I have found is :

# Here, BaseDocument is a 'raw' class
class BaseDocument():
    title = StringField()
    content = StringField()

# the targeted class inherits from MongoEngine's Document and our BaseDocument
class Derived1(Document, BaseDocument):
    author = StringField()
    def __init__(self):
        Document.__init__(self)
        BaseDocument.__init__(self)

And no more error at all and working properly as expected.