Back

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

I have the below db model:

from datetime import datetime

class TermPayment(models.Model):

# I have excluded fields that are irrelevant to the question

date = models.DateTimeField(default=datetime.now(), blank=True)

I add a new instance by using the below:

tp = TermPayment.objects.create(**kwargs)

My issue: all records in the database have the same value in the date field, which is the date of the first payment. After the server restarts, one record has the new date and the other records have the same as the first. It looks as if some data is cached, but I can't find where.

database: MySQL 5.1.25

Django v1.1.1

1 Answer

0 votes
by (106k points)
edited by

To solve the Django datetime issues you can use the datetime.now()function which is being evaluated when the model is defined, and not each time you add a record.

You can use the below mentioned piece of code:-

date = models.DateTimeField(auto_now_add=True, blank=True)

or

date = models.DateTimeField(default=datetime.now, blank=True)

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

Related questions

+1 vote
1 answer
asked Aug 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 25, 2019 in Salesforce by Kartik12234 (11.9k points)
0 votes
1 answer
0 votes
1 answer
asked Nov 29, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...