I'm trying to make a fork of MongoEngine that will allow auto updating of a DateTimeField
based on passing True to an auto_now
or auto_now_add
(a la Django).
So far I've added the attributes to the __init__
method of DateTimeField
like so:
def __init__(self, auto_now=None, auto_now_add=None, **kwargs):
self.auto_now, self.auto_now_add = auto_now, auto_now_add
super(DateTimeField, self).__init__(**kwargs)
Unfortunately, I cannot figure out how to populate this value cleanly when a document is created/saved. The only solution I see so far, is to add field specific behavior in BaseDocument's save or validate methods... But I don't like it.
Does anyone know of a better method?
By the way: I though of having a go at this after reading this question and @equinoxel's comment about extending mongo and being used to this attribute in django.
You could add a pre save signal and update the document date before saving.
class MyDoc(Document):
name = StringField()
updated_at = DateTimeField(default=datetime.datetime.now)
@classmethod
def pre_save(cls, sender, document, **kwargs):
document.updated_at = datetime.datetime.now()
signals.pre_save.connect(MyDoc.pre_save, sender=MyDoc)
The main issues with this is they wont be updated if you call update
or if you do bulk updates eg: MyDocs.objects.update(set__name=X)
Added ticket: https://github.com/MongoEngine/mongoengine/issues/110
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With