Mongoengine creation_time attribute in Document

后端 未结 9 1336
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 15:55

    One nice solution is reusing a single signal handler for multiple documents.

    class User(Document):
        # other fields...
        created_at = DateTimeField(required=True, default=datetime.utcnow)
        updated_at = DateTimeField(required=True)
    
    class Post(Document):
        # other fields...
        created_at = DateTimeField(required=True, default=datetime.utcnow)
        updated_at = DateTimeField(required=True)
    
    def update_timestamp(sender, document, **kwargs):
        document.updated_at = datetime.utcnow()
    
    signals.pre_save.connect(update_timestamp, sender=User)
    signals.pre_save.connect(update_timestamp, sender=Post)
    

    Be careful to assign a callable and not a fixed-value as the default, for example default=datetime.utcnow without (). Some of the other answers on this page are incorrect and would cause created_at for new documents to always be set to the time your app was first loaded.

    It's also always better to store UTC dates (datetime.utcnow instead of datetime.now) in your database.

提交回复
热议问题