我尝试使用创建和修改日期创建BaseDocument
:
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)
当我创建新的图书文档时:
>>> b = Book()
>>> b.id = '123'
>>> b.save()
<Book: Book object>
Mongo上未显示modified_at
字段:
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") }
我的方法有误吗?