[英]How to make custom field from django field
我想使我的自定義字段從Django外鍵擴展。
class CustomField(models.ForeignKey):
def __init__(self, *args, **kwargs):
self.type=kwargs.pop('type', None)
super(CustomField, self).__init__(*args, **kwargs)
我正在使用像
CustomField('User', type="test")
這可以正常工作,但是我想像這樣在我的字段中硬編碼模型名稱
super(CustomField, self).__init__('User', *args, **kwargs)
這樣我就可以使用
CustomField(type="test")
但是然后我得到這個錯誤
__init__() got multiple values for keyword argument 'to'
問題在於,當您調用super(CustomField, self).__init__('User', *args, **kwargs)
時,您將在self
和'User'參數中發送由models.ForeginKey使用的to
參數。 您可以嘗試通過以下方式進行操作:
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.