4

我正在尝试做一个非常简单的自定义字段,但似乎无法让它工作。

目前,我正在将此字段添加到我的应用程序中的几乎所有模型中。我希望将其指定为自定义字段以避免重复代码。

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

我浏览了推荐的网页,但似乎仍然找不到解决方法。任何帮助表示赞赏。谢谢。

4

1 回答 1

6

在描述您的领域时,您需要帮助 South。有两种方法可以做到这一点,如:http ://south.aeracode.org/wiki/MyFieldsDontWork

我首选的方法是在字段类上添加一个 South 字段三元组:

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

希望对您有所帮助。

于 2013-07-23T17:07:27.410 回答