简体   繁体   English

如何从Django字段中创建自定义字段

[英]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.

相关问题 如何使子类化的自定义Django表单字段不再需要? - How to make a subclassed, custom Django form field non-required? 如何显示自定义字段 - How to make a custom field appear Django 如何在给定 model 实例的自定义字段中调用方法? - Django how to call a method from a custom field given a model instance? 如何在django中制作从10000开始的自动增量字段 - How to make auto increment field in django which starts from 10000 如何在 html 页面的 django 的字段中进行过滤或自动完成 - how make a filter or autocomplete in a field in django from html page 在Django> = 1.10中初始化(未从DB加载)后立即访问字段时,如何创建自定义模型字段调用to_python? - How do I make a custom model Field call to_python when the field is accessed immediately after initialization (not loaded from DB) in Django >=1.10? Django自定义字段-从to_python方法获取模型字段 - Django custom field - get model field from to_python method Django Rest序列化器的自定义字段顺序? - Django Rest Order on custom field from serializer? Django ModelForm从其他字段生成字段 - Django ModelForm make field from other fields Django REST框架:如何使详细的字段名称与其field_name不同? - Django REST Framework: how to make verbose name of field differ from its field_name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM