0

How can I set the default value as current date and time in a model?

my model is :

class StudUni(models.Model):
    student_id = models.IntegerField(blank=True, null=True)
    uni_name = models.CharField(max_length=55, blank=True, null=True)
    last_updated = models.DateTimeField(blank=True)
Leman Kirme
  • 530
  • 1
  • 5
  • 19

3 Answers3

1
last_updated = models.DateTimeField(auto_now=True)

For more info you can check here:

Aathik
  • 69
  • 8
0
class StudUni(models.Model):
    student_id = models.IntegerField(blank=True, null=True)
    uni_name = models.CharField(max_length=55, blank=True, null=True)
    last_updated = models.DateTimeField(auto_now_add=True,blank=True)

This will set the current date and time whenever its saved

VATSAL JAIN
  • 561
  • 3
  • 18
  • Also instead of auto_now_add you can use auto_now=True . This will let you update the date whenever you call the save function – VATSAL JAIN Aug 05 '20 at 15:52
0

i suggest you adding two timestamps, one (date_created) to save the date the object is created (for once) and the other one (date_updated or last_updated) to keep track on updates:

try this code below:

from django.utils.translation import gettext_lazy as _

[..]

class StudUni(models.Model):
    student_id = models.IntegerField(blank=True, null=True)
    uni_name = models.CharField(max_length=55, blank=True, null=True)

    # timestamps
    date_created = models.DateTimeField(_('date created'), auto_now_add=True)
    last_updated = models.DateTimeField(_('last updated'), auto_now=True)
cizario
  • 3,995
  • 3
  • 13
  • 27