Michael Bates
Michael Bates

Reputation: 1934

Django migration with DateTimeField and timedelta default

I'm having trouble with setting a default datetime on one of my Django models

from django.db import models
from django.utils import timezone

class MyModel(models.Model):
    my_datetime = models.DateTimeField(default=timezone.now() + timezone.timedelta(+14))

The problem is everytime I run makemigrations it creates a new migration on that field, with the default value serialized to what that value equals now.

migrations.AlterField(
    model_name='mymodel',
    name='my_datetime',
    field=models.DateTimeField(default=datetime.datetime(2016, 2, 4, 5, 56, 7, 800721, tzinfo=utc)),
    )

Is there anyway I can set a default value for a DateTimeField that's in the future?

Upvotes: 5

Views: 4755

Answers (3)

from django.db import models
from django.utils import timezone

class MyModel(models.Model):
    my_datetime = models.DateTimeField(auto_add_now=True)

and migration when you run makemigrations

migrations.CreateModel(
    name='MyModel',
    fields=[
        ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
        ('my_datetime', models.DateTimeField(auto_now_add=True)),
    ],
),

Upvotes: 0

vanadium23
vanadium23

Reputation: 3586

Problem is that you put result of expression in default. Instead you need assign default to be callable for what you want. Here is an example:

from django.db import models
from django.utils import timezone

def default_time():
    return timezone.now() + timezone.timedelta(+14)

class MyModel(models.Model):

    my_datetime = models.DateTimeField(default=default_time)

Upvotes: 11

Eliot S Winchell
Eliot S Winchell

Reputation: 368

I'm new to Django so I can't come up with a solution from scratch for you. But this is an interesting problem so I did some googling and I think I found a question/answer with the exact same scenario as yours.

Django default=timezone.now + delta

"default takes a callable, so you just need to write a function to do what you want and then provide that as the argument:"

def one_day_hence():
    return timezone.now() + timezone.timedelta(days=1)

class MyModel(models.Model):
    ...
    key_expires = models.DateTimeField(default=one_day_hence)

Upvotes: 0

Related Questions