我正在尝试做一个非常简单的自定义字段,但似乎无法让它工作。
目前,我正在将此字段添加到我的应用程序中的几乎所有模型中。我希望将其指定为自定义字段以避免重复代码。
identifier = models.CharField(
max_length = 20,
unique = True, validators = [validators.validate_slug],
help_text = "Help text goes here."
)
我拥有的是:
class MyIdentifierField(models.CharField):
description = "random string goes here"
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 20
kwargs['unique'] = True
kwargs['validators'] = [validators.validate_slug]
kwargs['help_text'] = "custom help text goes here"
super(MyIdentifierField, self).__init__(*args, **kwargs)
def db_type(self, connection):
return 'char(25)'
所以我可以像这样使用它:
identifier = MyIdentifierField()
但是,当我python manage.py schemamigration --auto <myapp>
时,我收到以下错误:
! Cannot freeze field 'geral.seccao.identifier'
! (this field has class geral.models.MyIdentifierField)
! South cannot introspect some fields; this is probably because they are custom
! fields. If they worked in 0.6 or below, this is because we have removed the
! models parser (it often broke things).
! To fix this, read http://south.aeracode.org/wiki/MyFieldsDontWork
我已经浏览了推荐的网页,但似乎仍无法找到解决方法。任何帮助表示赞赏。感谢。
答案 0 :(得分:6)
在描述你的领域时,你需要帮助南方。有两种方法可以执行此操作,如http://south.aeracode.org/wiki/MyFieldsDontWork
所述我首选的方法是在字段类上添加南字段三元组:
def south_field_triple(self):
try:
from south.modelsinspector import introspector
cls_name = '{0}.{1}'.format(
self.__class__.__module__,
self.__class__.__name__)
args, kwargs = introspector(self)
return cls_name, args, kwargs
except ImportError:
pass
希望能帮到你。