2014-09-20 38 views
5

序列化classmethods当我尝试在Django的1.7运行manage.py makemigrations,我得到以下错误:在Django 1.7

ValueError: Cannot serialize: <bound method ModelBase.get_default of <class 'printapp.models.JobConfiguration'>> 
There are some values Django cannot serialize into migration files. 
For more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing 

因此,它看起来像有与方法get_default是对JobConfiguration定义,其定义是一个问题重复如下:

@classmethod 
def get_default(cls): 
    result = cls() 
    result.save() 
    return result 

link that was provided in the error message,它看起来像序列化“类引用”是一个支持的功能。

“类参考”与@classmethod相同吗?

我该如何在“模块的顶级范围”中放置“类参考”?

为什么必须通过迁移来跟踪方法?我的假设是迁移是针对数据库模式的,它只跟踪存储的数据类型,而不是类使用的方法类型。

有意思的是:将get_default的定义更改为静态方法,下面重复解决了这个问题,但代价是必须对JobConfiguration类名进行硬编码。

@staticmethod 
def get_default(): 
    result = JobConfiguration() 
    result.save() 
    return result 

(一些上下文:此方法被引用作为JobConfiguration.get_defaultmodels.OneToOneField(JobConfiguration, default=JobConfiguration.get_default)内与创建用于创建这些字段中的每一个新的JobConfiguration的效果)

+1

出于兴趣,这会给你什么'JobConfiguration.objects.create()'?这仍然是一个命令,几乎没有更多的打字。 – 2014-09-20 08:08:47

+0

呵呵,我没有意识到这种方法是可用的。我可能会在我的代码中更改它,但我仍然有兴趣知道代码为什么会失败。 – Z1MM32M4N 2014-09-21 09:05:38

回答

0

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.

类方法是结合班上。由于装饰器封装了方法,序列化程序面临着不确定性:绑定器或方法,并且失败。使用静态方法不存在这样的问题,因为它是附加到类的简单函数。