0

Using Django 1.11 I'd like to make a custom model field that inherits from ForeignKey.

With a normal ForeignKey, you can do something like the following:

class Car(models.Model):
    manufacturer = models.ForeignKey(Company)

Instead, I'd like to make a model field that is largely the same as the ForeignKey field, but 1) uses a different default widget for the formfield and 2) doesn't require the model name to be placed as a positional parameter.

# myapp/models.py
from otherapp.fields import ManufacturerField

class Car(models.Model):
    manufacturer = ManufacturerField()

Unfortunately, I'm having a hard time overriding the init method of the child class to get my "Company" model inserted into the mix. Here's what I have so far by way of a modelfield (not working on the widget at all yet):

# otherapp/fields.py
from otherapp.models import Company

class ManufacturerField(models.ForeignKey):

def __init__(self, *args, **kwargs):
    return super(ContentField, self).__init__(Company, **kwargs)

When I try to do this, I get:

TypeError: Couldn't reconstruct field manufacturer on myapp.Car: __init__() got multiple values for argument 'to'

Is there a property I can set on the custom modelfield class to specify that I want this to be a foreignkey to one specific model? If not, any ideas on how I can properly intercept the init method to feed in my model?

Robert Townley
  • 3,414
  • 3
  • 28
  • 54

1 Answers1

0

super() referring to the base class explicitly. you can see this question to understand it.

def __init__(self, *args, **kwargs):
    return super(ContentField, self).__init__(Company, **kwargs)

should be;

def __init__(self, *args, **kwargs):
    return super(ManufacturerField, self).__init__(*args, **kwargs)

Here is an example how to custom the field.

binpy
  • 3,994
  • 3
  • 17
  • 54