本文介绍了文档中的Mongoengine creation_time属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在文档中添加creation_time
属性.以下是一个示例:
I am trying to add a creation_time
attribute to my documents. The following would be an example:
import datetime
class MyModel(mongoengine.Document):
creation_date = mongo.DateTimeField()
modified_date = mongo.DateTimeField(default=datetime.datetime.now)
Django模型为其DateTimeField
对象(例如add_now
等)内置参数,但是MongoEngine不支持此功能.
Django models have built in parameter for their DateTimeField
objects like add_now
, etc.,but MongoEngine does not support this.
我想知道做到这一点的最佳方法是:
I am wondering if best way to do this is the following:
m,created = MyModel.objects.get_or_create()
if created:
m.creation_date = datetime.datetime.now()
或者有更好更好的方法.
or if there is a better, nicer way.
推荐答案
您可以覆盖save方法.
You could override the save method.
class MyModel(mongoengine.Document):
creation_date = mongo.DateTimeField()
modified_date = mongo.DateTimeField(default=datetime.datetime.now)
def save(self, *args, **kwargs):
if not self.creation_date:
self.creation_date = datetime.datetime.now()
self.modified_date = datetime.datetime.now()
return super(MyModel, self).save(*args, **kwargs)
这篇关于文档中的Mongoengine creation_time属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!