Django 1.7.1 Makemigrations fails when using lambda as default for attribute

纵饮孤独 提交于 2019-12-30 02:44:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/27072222/django-1-7-1-makemigrations-fails-when-using-lambda-as-default-for-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!