Mixin based mongoengine docs with class decorators instead of using multiple inheritance

Suppose I am using Mongoengine to generate documents like this:

class Tag(Document):
    name = fields.StringField(required=True, unique=True)
    user = fields.ReferenceField('User')
    created = fields.DateTimeField()
    updated = fields.DateTimeField(default=datetime.datetime.now)

      

created

and updated

are fields that are often used in other models, and I want to split the code for date-related stuff in the "mixin". Using multiple inheritance is one solution:

class Tag(Timestampable, Document):
    name = fields.StringField(required=True, unique=True)
    user = fields.ReferenceField('User')

class Timestampable()
    created = fields.DateTimeField()
    updated = fields.DateTimeField(default=datetime.datetime.now)

      

While this works, Python's multiple inheritance has its own serious drawbacks . Therefore, we need a different solution. Cool decorators came to my mind:

@Timestampable
class Tag(Document):
    name = fields.StringField(required=True, unique=True)
    user = fields.ReferenceField('User')

def Timestampable(cls)
    cls.created = fields.DateTimeField()
    cls.updated = fields.DateTimeField(default=datetime.datetime.now)
    return cls

      

This is cool because I don't have to worry about any calls super

.

However, this doesn't work. Both are DateTimeField

not created when referencing the class Tag

.

Is there any solution to my problem?

application

To correctly understand the need for this, here is the complete mixin code for the Timestampable decorator:

def Timestampable(cls):
    cls.created = model_fields.DateTimeField()
    cls.updated = model_fields.DateTimeField(default=datetime.datetime.now)

    cls_save = cls.save
    def save(self, *args, **kwargs):
        now = datetime.datetime.now()
        if not self.id:
            self.created = now
        self.updated = now
        return cls_save(self, *args, **kwargs)
    cls.save = save

    return cls

      

+3


source to share





All Articles