自定义字段 - 为关键字参数获得多个值' ressect_name'
我正在开发一个自定义字段,它只是指向 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
,然后使用所有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
字段时都指定它。
I'm working on a custom field that is just a shortcut to ForeignKey
that points to addresses.Country
model.
When I run makemigrations
it returns this error with I'm not sure:
TypeError: Couldn't reconstruct field rsft_country on properties.Property: django.db.models.fields.related.ForeignKey.__init__() got multiple values for keyword argument 'to'
I understand that there are two to
arguments passed but I don't understand why. It looks like the field is initialized two times. Once with the kwargs
I provided and then with all the 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)
Model:
...
rsft_country = addresses_fields.RsftCountryField(null=True, blank=True)
It prints kwargs
two times:
{'null': True, 'blank': True}
{'blank': True, 'null': True, 'related_name': '+', 'on_delete': <function PROTECT at 0x7fa9fa277d00>, 'to': 'addresses.country'}
Why does it do that and how to make it work?
EDIT:
Basically, I just want to provide all the fields by default without having to specify it everytime I define the country
field in model.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是
。 deconstruct()
方法&nbsp; [django-doc] ,因为这样做:您将需要进行新的迁移,而
rsftcountryfield
>涉及。The problem is the
.deconstruct()
method [Django-doc], since that will :You will need to make new migrations where a
RsftCountryField
is involved.