Creating automatic datetime in django

Viewed 148

I would like to create a field with a predefined datetime. Something like this:

class MyExample(models.Model):
    expiration = timezone.now() + timedelta(days=1)
    expiration_date = models.DateTimeField(verbose_name="Expirate in", default=expiration)
    ...

I don't know if it's the best way, because when there are new migrations there is an update of the table with the expiration.

Does anyone have any tips?

1 Answers

You here set expiration date to the timestamp one day after you start the server. But if you thus run the server for a week, all expiration_dates will already expire before the timestamp when you create MyExample.

You should define a function that returns the expiration date, and pass a reference to that function as default:

from datetime import timedelta
from django.utils.timezone import now

def expiration():
    return now() + timedelta(days=1)

class MyExample(models.Model):
    expiration_date = models.DateTimeField(
        default=expiration,
        verbose_name='Expirate in'
    )
Related