Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (47.6k points)

For Django 1.1.

I have this in my models.py:

class User(models.Model):

created = models.DateTimeField(auto_now_add=True)

modified = models.DateTimeField(auto_now=True)

When updating a row I get:

[Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base.py:84: Warning: Column 'created' cannot be null [Sun Nov 15 02:18:12 2009] [error] return self.cursor.execute(query, args)

The relevant part of my database is:

`created` datetime NOT NULL,

`modified` datetime NOT NULL,

Is this cause for concern?

1 Answer

0 votes
by (106k points)
edited by

It is recommended not using auto_now or auto_now_add and instead of these you can define your own save() method to make sure that it is only updated if the id is not set such as when the item is first created), and have it update modified every time the item is saved.

You can follow the below-mentioned code:-

from django.utils import timezone

class User(models.Model):

created = models.DateTimeField(editable=False)

modified = models.DateTimeField()

def save(self, *args, **kwargs): 

if not self.id:

self.created = timezone.now()

self.modified = timezone.now()

return super(User, self).save(*args, **kwargs)

I hope this will help you.

To know more about this you can have a look at the following video:-

Related questions

+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 28, 2020 in Python by Rekha (2.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...