我使用的是 Django 1.7.1。我的模型如下所示:
from datetime import datetime
from django.db import models
class myModel(models.Model):
x = models.CharField(max_length=254,null=True, blank=True,)
一切都运行得很好。
但是,当我将以下属性添加到 myModel 时,它会中断:
y = models.DateTimeField(default=lambda: datetime.utcnow() + timedelta(days=1), editable=False)
manage.py makemigrations
给出以下错误:
ValueError: Cannot serialize function: lambda
这似乎是一个已知的错误:http://comments.gmane.org/gmane.comp.python.django.scm/125724
那么我该如何解决这个问题呢?我需要将 y
的值默认自动设置为从模型创建之日起的 24 小时。
最佳答案
migrations documentation解决这个问题:
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
因此解决方案很简单:定义一个常规函数并按名称引用它,而不是使用 lambda。
def one_day_hence():
return datetime.utcnow() + timezone.timedelta(days=1)
class MyModel(models.Model):
y = models.DateTimeField(default=one_day_hence)
关于python - 使用 lambda 作为属性的默认值时,Django 1.7.1 Makemigrations 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27072222/