python - 使用 lambda 作为属性的默认值时,Django 1.7.1 Makemigrations 失败

标签 python django django-models lambda django-migrations

我使用的是 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/

相关文章:

python - 值错误: too many values to unpack (expected 2

python - 导入优先级一致性?

django - 具有两个 URL 和两个不同 SSL 证书的 Apache

python - F 表达式列表的求和

python - 需要帮助将小型 python 脚本从 Windows 转换为 Linux

python - 使用 scrapy python 进行递归抓取

python - Django : Passing api's json to template for use in a table

Django A/B 拆分测试包(我发现没有一个是有据可查的和最新的。)

django - 覆盖保存方法 - 'ImageFile' 对象没有属性 '_committed'

Django:验证上传文件的文件类型