1

I'm trying to create a BaseDocument with creation and modification dates:

from datetime import datetime
from mongoengine import DateTimeField, Document, StringField, signals


class BaseDocument(Document):
    created_at = DateTimeField(default=datetime.utcnow)
    modified_at = DateTimeField()

    @classmethod
    def post_save(cls, sender, document, **kwargs):
        document.modified_at = datetime.utcnow()

    meta = {
        'abstract': True,
        'allow_inheritance': True
    }


signals.post_save.connect(BaseDocument.post_save, sender=BaseDocument)


class Book(BaseDocument):
    id = StringField(primary_key=True)

When I create a new Book document:

>>> b = Book()
>>> b.id = '123'
>>> b.save()
<Book: Book object>

The modified_at field is not shown on Mongo:

MongoDB shell version v3.4.0-rc2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0-rc2
> use test
switched to db test
> db.book.find()
{ "_id" : "123", "_cls" : "Book", "created_at" : ISODate("2016-11-08T18:17:20.761Z") }

Is my approach wrong?

César
  • 9,939
  • 6
  • 53
  • 74
  • Possible duplicate of [How to use Django model inheritance with signals?](http://stackoverflow.com/questions/7792287/how-to-use-django-model-inheritance-with-signals) – Назар Топольський Nov 08 '16 at 19:18
  • Thanks, but I'm not using Django models – César Nov 08 '16 at 20:56
  • Yeah, it probably isn't really a duplicate. However, the issue might not be with models themselves, but with the dispatcher. If you use Django signals (it seems like that), then the dispatcher does not check for subclasses for `sender` (like by using `isinstance`), more like doing `sender.__class__ == sender_class`. So you might wanna take the one of the approaches suggested in that answer. – Назар Топольський Nov 08 '16 at 21:49

0 Answers0