75π
You could override the save method.
class MyModel(mongoengine.Document):
creation_date = mongo.DateTimeField()
modified_date = mongo.DateTimeField(default=datetime.datetime.now)
def save(self, *args, **kwargs):
if not self.creation_date:
self.creation_date = datetime.datetime.now()
self.modified_date = datetime.datetime.now()
return super(MyModel, self).save(*args, **kwargs)
28π
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.
- [Django]-Naming Python loggers
- [Django]-Exclude a field from django rest framework serializer
- [Django]-Django abstract models versus regular inheritance
6π
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.
- [Django]-Pipfile.lock out of date
- [Django]-Where's my JSON data in my incoming Django request?
- [Django]-Django admin: override delete method
4π
# -*- coding: utf-8 -*-
from mongoengine import *
from mongoengine import signals
from datetime import datetime
class User(Document):
email = StringField(required=True, unique=True)
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)
# audit fields
created_on = DateTimeField(default=datetime.now())
updated_on = DateTimeField(default=datetime.now())
@classmethod
def pre_save(cls, sender, document, **kwargs):
document.updated_on = datetime.now()
signals.pre_save.connect(User.pre_save, sender=User)
- [Django]-Can the Django ORM store an unsigned 64-bit integer (aka ulong64 or uint64) in a reliably backend-agnostic manner?
- [Django]-Use get_queryset() method or set queryset variable?
- [Django]-Django β Excluding some fields in Inline Admin Interface
4π
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)
- [Django]-Python string to Django timezone (aware datetime)
- [Django]-Handle `post_save` signal in celery
- [Django]-How can I serialize a queryset from an unrelated model as a nested serializer?
4π
My preferred solution is to use the @property
decorator to return the creation datetime as extracted from the ObjectId:
@property
def creation_stamp(self):
return self.id.generation_time
- [Django]-Serving Media files during deployment in django 1.8
- [Django]-Is it possible to generate django models from the database?
- [Django]-How can I disable logging while running unit tests in Python Django?
1π
Try use lambda value:
import datetime
from mongoengine import Document
class MyModel(Document):
creation_date = mongo.DateTimeField()
modified_date = mongo.DateTimeField(default=lambda : datetime.datetime.now())
- [Django]-What does error mean? : "Forbidden (Referer checking failed β no Referer.):"
- [Django]-Django: Invalid filter
- [Django]-What is the difference between {% load staticfiles %} and {% load static %}
0π
Traditionally, Iβve set the creation_date
default to datetime.now()
and then have hidden the field on the admin form so you remove the possibility of a user overwriting the correct value. That requires almost no code.
Overriding the save method as suggested by Willian is also effective since you can programmtically block any updates to the creation_date
and update the modfied_date
at the same time.
- [Django]-When to use get, get_queryset, get_context_data in Django?
- [Django]-Django β How to access the verbose_name of a Model in its Admin Module?
- [Django]-Manually logging in a user without password
-8π
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)
- [Django]-AngularJS with Django β Conflicting template tags
- [Django]-How to implement a "back" link on Django Templates?
- [Django]-Create custom buttons in admin change_form in Django