Mongoengine creation_time attribute in Document

后端 未结 9 1342
Happy的楠姐
Happy的楠姐 2020-12-14 15:50

I am trying to add a creation_time attribute to my documents. The following would be an example:

import datetime

class MyModel(mongoengine.Docu         


        
9条回答
  •  我在风中等你
    2020-12-14 16:15

    If you are using the timestamp field in a bunch of Documents you can keep your code DRY by creating an abstract Document instead.

    from datetime import datetime
    from mongoengine import Document
    
    class CreateUpdateDocument(Document):
        meta = {
            'abstract': True
        }
    
        # last updated timestamp
        updated_at = DateTimeField(default=datetime.now)
    
        # timestamp of when entry was created
        created_at = DateTimeField(default=datetime.now)
    
        def save(self, *args, **kwargs):
            if not self.created_at:
                self.created_at = datetime.now()
            self.updated_at = datetime.now()
            return super(CreateUpdateDocument, self).save(*args, **kwargs)
    

提交回复
热议问题