简体   繁体   中英

How to make custom field from django field

I want to make my custom field extend from django foreign key.

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) . 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM