[英]How to make custom field from django field
I want to make my custom field extend from django foreign key. 我想使我的自定义字段从Django外键扩展。
class CustomField(models.ForeignKey):
def __init__(self, *args, **kwargs):
self.type=kwargs.pop('type', None)
super(CustomField, self).__init__(*args, **kwargs)
I am using like 我正在使用像
CustomField('User', type="test")
This works correctly but i want to hard code model name in my field like this 这可以正常工作,但是我想像这样在我的字段中硬编码模型名称
super(CustomField, self).__init__('User', *args, **kwargs)
so that i can use 这样我就可以使用
CustomField(type="test")
but then i get this error 但是然后我得到这个错误
__init__() got multiple values for keyword argument 'to'
The problem is that your are sending the to
parameter used by models.ForeginKey in self
and in the 'User' parameter when you make call super(CustomField, self).__init__('User', *args, **kwargs)
. 问题在于,当您调用super(CustomField, self).__init__('User', *args, **kwargs)
时,您将在self
和'User'参数中发送由models.ForeginKey使用的to
参数。 You can try to do in this way: 您可以尝试通过以下方式进行操作:
class CustomField(models.ForeignKey):
def __init__(self, *args, **kwargs):
kwargs['to'] = 'User'
self.type = kwargs.pop('type', None)
super(CustomField, self).__init__(*args, **kwargs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.