0

I want to define a base Document to define some public filed and method. But I found the child Document can't define it's custom name when inheritance. such as:

from mongoengine import *

class BaseInfo(Document):
    account = StringField()
    insert_time = IntField()
    update_time = IntField()
    meta = {'allow_inheritance': True}

class SonItem(Document, BaseItem):
   age = IntField()
   meta = {'collection': 'son_item'}
   meta = {'allow_inheritance': True}


class GrandItem(Document, BaseItem):
    age = IntField()
    meta = {'collection': 'grand_item'}

This will comes the error:

SyntaxWarning: Trying to set a collection on a subclass (SonItem)
C.shayv
  • 51
  • 5

1 Answers1

2

If you want your BaseInfo (shouldn't it be BaseItem?) to be essentially a mixin class, you should define it as abstract as per docs here.

class BaseItem(Document):
    account = StringField()
    insert_time = IntField()
    update_time = IntField()
    meta = {'abstract': True}

If you specify the class as a base with allow_inheritance the assumption is that the subclasses will be in the same collection. That way you can search for objects using the base and it will correctly retrieve all the subclasses as well. You cannot do that across collections.

Roman Kutlak
  • 2,684
  • 1
  • 19
  • 24