In django - is there a default timestamp field for all objects? That is, do I have to explicitly declare a 'timestamp' field for 'created on' in my Model - or is there a way to get this automagically?
TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.
default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).
Fields in Django are the data types to store a particular type of data. For example, to store an integer, IntegerField would be used. These fields have in-built validation for a particular data type, that is you can not store “abc” in an IntegerField.
No such thing by default, but adding one is super-easy. Just use the auto_now_add
parameter in the DateTimeField
class:
created = models.DateTimeField(auto_now_add=True)
You can also use auto_now
for an 'updated on' field. Check the behavior of auto_now
here.
For auto_now_add
here.
A model with both fields will look like this:
class MyModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
Automagically doesn't sound like something django would do by default. It wouldn't force you to require a timestamp.
I'd build an abstract base class and inherit all models from it if you don't want to forget about the timestamp / fieldname, etc.
class TimeStampedModel(models.Model): created_on = models.DateTimeField(auto_now_add=True) class Meta: abstract = True
It doesn't seem like much to import wherever.TimeStampedModel
instead of django.db.models.Model
class MyFutureModels(TimeStampedModel): ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With