gpt4 book ai didi

python - Django 1.7迁移无法序列化类方法

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:09 27 4
gpt4 key购买 nike

我有一个非常基本的类,如下所示:

class Car(Model):

name = CharField(max_length=255, unique=True)

@classmethod
def create_simple_examples(cls):
for c in ['Sedan', 'Coupe', 'Van', 'SUV']:
cls.objects.get_or_create(name=c)

@classmethod
def get_default(cls):
c, _ = cls.objects.get_or_create(name='Sedan')
return c

def __unicode__(self):
return self.name

我正在尝试将它添加到 Django 应用程序中。我有两个类方法:1. 快速填充表格的函数,以及 2. 获取经常使用的默认函数。

当我运行时

python manage.py makemigrations myapp

出现以下错误

ValueError: Cannot serialize: <bound method ModelBase.get_default of <class 'crunch.django.myapp.models.Car'>>

我不太清楚为什么它要尝试序列化我的 get_default 函数,因为这实际上并不是表本身迁移的一部分。任何帮助将不胜感激

更新 我想我可能已经找到了问题的根源(尽管仍然不确定如何解决...)

我有其他类 FKing 到我的新类,默认使用我上面的默认值......像这样

class OtherClass(Model):

car = ForeignKey(Car, default=Car.get_default)

看起来迁移正因此尝试序列化函数。关于如何解决这个问题的任何提示?

最佳答案

@deconstructible 装饰器添加到具有classmethod 的类

from django.utils.deconstruct import deconstructible

@deconstructible
class Car(Model):
...

关于 deconstructible 的更多文档可以在这里找到

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

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