Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update DateTime field in mongoengine with auto_now_add

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.

like image 569
tutuDajuju Avatar asked Sep 01 '12 17:09

tutuDajuju


1 Answers

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

like image 119
Ross Avatar answered Sep 18 '22 12:09

Ross