Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In django do models have a default timestamp field?

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?

like image 483
9-bits Avatar asked Nov 04 '11 22:11

9-bits


People also ask

What is timestamp model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.

What is default in Django model?

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).

What is Django DB models fields?

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.


2 Answers

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) 
like image 65
MoshiBin Avatar answered Sep 26 '22 08:09

MoshiBin


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):     .... 
like image 26
Yuji 'Tomita' Tomita Avatar answered Sep 26 '22 08:09

Yuji 'Tomita' Tomita