why created_at is greater than updated_at while inserting data in table

197 views
Skip to first unread message

Ankit Khandewal

unread,
Nov 28, 2018, 2:13:03 AM11/28/18
to Django users
hello, i am using this code to update created_at and updated_at in models:
        created_at = models.DateTimeField(auto_now_add=True)
updated_at= models.DateTimeField(auto_now=True,null=True)

but however there is created _at is greater than updated_at when data is inserted: 

       created_at  -> 2018-11-26 11:11:30.020989
       updated_at -> 2018-11-26 11:11:30.019762

please help, thank you.

Nelson Varela

unread,
Nov 28, 2018, 9:20:33 AM11/28/18
to Django users
I think it has to do with django adding timezone.now() on each field with auto_now on it when saving to the databse.. the code for the first field will get timezone.now() slightly earlier then the second one 

Ankit Khandewal

unread,
Nov 28, 2018, 9:48:59 AM11/28/18
to Django users
is there any fix to this?

Ankit Khandewal

unread,
Nov 28, 2018, 11:05:30 PM11/28/18
to Django users
and with this method created_at and updated_at both arguments will trigger the field update event with timezon.now(), is there any other method to enter only created_at at time of inserting 


On Wednesday, 28 November 2018 12:43:03 UTC+5:30, Ankit Khandewal wrote:

Gerson David Vizquel Alemán

unread,
Nov 29, 2018, 1:45:26 PM11/29/18
to Django users
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()

def save(self, *args, **kwargs):
    ''' On save, update timestamps '''
    if not self.id:
        self.created_at = timezone.now()
        self.updated_at = self.created_at
    self.updated_at = timezone.now()
    return super(User, self).save(*args, **kwargs)
Reply all
Reply to author
Forward
0 new messages