在Django1.7中序列化类方法

2024-10-02 12:35:27 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图在Django 1.7上运行manage.py makemigrations时,我得到以下错误:

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

因此,在JobConfiguration上定义的方法get_default有问题,其定义在下面重复:

^{pr2}$

link that was provided in the error message之后,序列化“类引用”似乎是一个受支持的功能。在

类引用与@classmethod相同吗?

如何将“类引用”放入“模块的顶层作用域”?

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

值得注意的是:将get_default的定义更改为下面重复的静态方法可以解决问题,但代价是必须硬编码JobConfiguration类名。在

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

(一些上下文:此方法在models.OneToOneField(JobConfiguration, default=JobConfiguration.get_default)中被引用为JobConfiguration.get_default,其效果是为每个创建的字段创建一个新的JobConfiguration。)


Tags: django方法pydefaultget定义managemodels
1条回答
网友
1楼 · 发布于 2024-10-02 12:35:27

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.

类方法绑定到类。因为decorator包装了方法,所以序列化程序面临着一个不明确的问题:包装器还是方法,结果失败了。对于静态方法,不存在这样的问题,因为它是附加到类的一个简单函数。在

相关问题 更多 >

    热门问题