Django 1.7.1当使用lambda作为属性的默认值时,Makemigrations失败 [英] Django 1.7.1 Makemigrations fails when using lambda as default for attribute

查看:334
本文介绍了Django 1.7.1当使用lambda作为属性的默认值时,Makemigrations失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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 给我以下错误: p>

  ValueError:无法序列化功能:lambda 

这似乎是一个已知的错误: http: //comments.gmane.org/gmane.comp.python.django.scm/125724



那么我该如何解决呢?默认情况下,需要将 y 的值自动设置为创建模型之后的24小时。

解决方案

迁移文件解决这个问题:


迁移只是包含你的模型的旧定义的Python文件 - 因此,为了写它们,Django必须您的模型的当前状态并将其序列化为一个文件。虽然Django可以序列化大部分的事情,但有一些事情我们无法序列化为一个有效的Python表示....



Django可以序列化以下内容:任何函数或方法参考



Django无法序列化:Lambdas


所以解决方案很简单:只需在模块范围内定义函数,而不是使用lambda。


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.CharField(max_length=254,null=True, blank=True,)

Everything works perfectly fine.

However, when I add the following attribute to myModel, it breaks:

    y = models.DateTimeField(default=lambda: datetime.utcnow() + timedelta(days=1), editable=False)

manage.py makemigrations gives me the following error:

ValueError: Cannot serialize function: lambda

This seems like a known bug: http://comments.gmane.org/gmane.comp.python.django.scm/125724

So how can I work around it? I need the value of y to be automatically set by default to 24 hours from the moment the model was created.

解决方案

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

Django cannot serialize: Lambdas

So the solution is simple: just define the function in module scope rather than using a lambda.

这篇关于Django 1.7.1当使用lambda作为属性的默认值时,Makemigrations失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆