Mongoengine creation_time attribute in Document

后端 未结 9 1328
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:14

    As an aside, the creation time is stamped into the _id attribute - if you do:

    YourObject.id.generation_time
    

    Will give you a datetime stamp.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-14 16:18

    You could use auto_now_add parameter as per documentation:

    class MyModel(mongoengine.Document):
        creation_date = mongo.DateTimeField(auto_now_add = True)
        modified_date = mongo.DateTimeField(auto_now = True)
    
    0 讨论(0)
提交回复
热议问题