Django 1.7.1 Makemigrations fails when using lambda as default for attribute

后端 未结 1 1780
时光说笑
时光说笑 2020-12-30 22:22

I\'m using Django 1.7.1. My model looks like this:

from datetime import datetime
from django.db import models

class myModel(models.Model):
    x = models.Ch         


        
相关标签:
1条回答
  • 2020-12-30 23:18

    The migrations documentation addresses this:

    Migrations are just Python files containing the old definitions of your models - thus, to write them, Django must take the current state of your models and serialize them out into a file. While Django can serialize most things, there are some things that we just can’t serialize out into a valid Python representation....

    Django can serialize the following: Any function or method reference... in module’s top-level scope

    Django cannot serialize: Lambdas

    So the solution is simple: instead of a lambda, define a regular function and refer to it by name.

    def one_day_hence():
        return datetime.utcnow() + timezone.timedelta(days=1)
    
    class MyModel(models.Model):
        y = models.DateTimeField(default=one_day_hence)
    
    0 讨论(0)
提交回复
热议问题