How to Create a Timestamp and Last Updated Database Table Fields in Django 


               


How to Create a Timestamp and Last Updated Database Table Fields in Django



Python


In this article, we show how to create a timestamp and last updated database fields in Django that stores the time (to the minute) when a field was submitted and when (if it is) updated.

A timestamp for a database table is useful because it can show when the entry was first added to the database.

Usually, when you have a timestamp (when the entry was first made), you would want an updated field, which shows when the entry was last updated.

We'll show how to do both of these in this article. We'll create a timestamp database field and an updated database field.

So, let's go to our models.py file, where we create the database table.


models.py File

The database table we will create is called MemberComment.

In this database table, we create a field called comment, timestamp, and updated.

The code is shown below.



So to create our database table, we have to import models from django.db

We then create a database table called MemberComment.

We create 3 fields: comment, timestamp, and updated.

We make comment a text field, where user can type in comments.

timestamp is set equal to, models.DateTimeField (auto_now_add=True)

What this does is it adds the current time (to minutes) of the database table field of the time when the comment was submitted.

updated is set equal to, models.DateTimeField(auto_now= True).

What this does is it adds the time that it currently is when the field is updated.

The distinction is auto_now_add is a one-time action (at the time of creation), while auto_now updates each time the form is updated.

So, that's all it takes. You just have to do the necessary migrations and then run the server.

You then can register these fields into admin in the admin.py page, using the following code.



Once you register it, you will see the following output, shown below.

Timestamp and last updated database table fields in Django

And this is how you can create a timestamp and last updated database table fields in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...