gpt4 book ai didi

python - 在 Django 1.7 中序列化类方法

转载 作者:太空狗 更新时间:2023-10-30 01:38:06 25 4
gpt4 key购买 nike

当我尝试在 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 有问题,其定义在下面重复:

@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

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

最佳答案

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.

类方法绑定(bind)到类。由于装饰器包装了方法,序列化器面临着绑定(bind)什么的歧义:包装器或方法,它失败了。使用静态方法就没有这样的问题,因为它是一个附加到类的简单函数。

关于python - 在 Django 1.7 中序列化类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25946602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com