0

I have a model like this:

MyModel(models.Model):
    ...
    date_start = models.DateTimeField(
        auto_now=True,
        editable=True
    )

    date_end = models.DateTimeField(
        default=datetime.now() + relativedelta(months=3)
    )

...

I modified the date_end field before, and I did the migrations, it is working properly, but now it is still detecting that change as a new migration. Any idea? Thanks in advance.

Gocht
  • 9,924
  • 3
  • 42
  • 81

1 Answers1

0

The problem is that you are calling datetime.now() in the default parameter of the definition. That means that the default changes each time you start Django, so the system thinks you need a new migration.

You should wrap that calculation into a lambda function, which will be called as necessary:

date_end = models.DateTimeField(
    default=lambda: datetime.now() + relativedelta(months=3)
)

Edit

If the lambda causes problems, you can move the code into a separate function and pass that as the default instead:

def default_end():
    return datetime.now() + relativedelta(months=3)

...

date_end = models.DateTimeField(
        default=default_end
)

Note here we're passing the function object, not the result, as the default param.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • That was the problem, but is there other way to define it? I used lambda but I got `ValueError: Cannot serialize function: lambda` – Gocht Jun 19 '15 at 17:39
  • Sorry for asking again.. but I have defined `default_end` inside and outside `MyModel` class but I got error when I run `makemigrations` – Gocht Jun 19 '15 at 17:54