我正在开发一个自定义字段,它只是指向addresses.Country
模型的ForeignKey
的快捷方式。
当我运行makemigrations
时,它会返回这个错误,我不确定:
TypeError: Couldn't reconstruct field rsft_country on properties.Property: django.db.models.fields.related.ForeignKey.__init__() got multiple values for keyword argument 'to'
我知道有两个to
论点通过了,但我不明白为什么。看起来该字段被初始化了两次。一次是我提供的kwargs
,然后是所有的夸尔格。
class RsftCountryField(models.ForeignKey):
def __init__(self, verbose_name=None, **kwargs):
print(kwargs)
kwargs['verbose_name'] = verbose_name or 'Krajina'
to = 'addresses.Country'
on_delete = kwargs.pop('on_delete',None) or models.PROTECT
related_name = kwargs.pop('related_name',None) or '+'
super().__init__(to, on_delete, related_name=related_name, related_query_name=None,
limit_choices_to=None, parent_link=False, to_field=None,
db_constraint=True, **kwargs)
型号:
...
rsft_country = addresses_fields.RsftCountryField(null=True, blank=True)
它打印kwargs
两次:
{'null': True, 'blank': True}
{'blank': True, 'null': True, 'related_name': '+', 'on_delete': <function PROTECT at 0x7fa9fa277d00>, 'to': 'addresses.country'}
它为什么要这样做,以及如何让它发挥作用?
编辑:
基本上,我只想默认提供所有字段,而不必每次在模型中定义country
字段时都指定它。
问题是.deconstruct()
方法[Django-doc],因为这将:
class RsftCountryField(models.ForeignKey):
def __init__(self, verbose_name=None, **kwargs):
kwargs['verbose_name'] = verbose_name or 'Krajina'
to = 'addresses.Country'
on_delete = kwargs.pop('on_delete',None) or models.PROTECT
related_name = kwargs.pop('related_name', None) or '+'
super().__init__(
to,
on_delete,
related_name=related_name,
related_query_name=None,
limit_choices_to=None,
parent_link=False,
to_field=None,
db_constraint=True,
**kwargs
)
defdeconstruct(self):
name, path, args, kwargs = super().deconstruct()
kwargs.pop('to', None)
kwargs.pop('related_query_name', None)
kwargs.pop('limit_choices_to', None)
kwargs.pop('parent_link', None)
kwargs.pop('to_field', None)
kwargs.pop('db_constraint', None)
returnname, path, args, kwargs
在涉及RsftCountryField
的情况下,您将需要进行新的迁移。