Skip to content
Advertisement

Custom field – got multiple values for keyword argument ‘related_name’

I’m working on a custom field that is just a shortcut to ForeignKey that points to addresses.Country model.

When I run makemigrations it returns this error with I’m not sure:

TypeError: Couldn't reconstruct field rsft_country on properties.Property: django.db.models.fields.related.ForeignKey.__init__() got multiple values for keyword argument 'to'

I understand that there are two to arguments passed but I don’t understand why. It looks like the field is initialized two times. Once with the kwargs I provided and then with all the kwargs.

class RsftCountryField(models.ForeignKey):
    def __init__(self, verbose_name=None, **kwargs):
        print(kwargs)
        kwargs['verbose_name'] = verbose_name or 'Krajina'
        to = 'addresses.Country'
        on_delete = kwargs.pop('on_delete',None) or models.PROTECT
        related_name = kwargs.pop('related_name',None) or '+'
        super().__init__(to, on_delete, related_name=related_name, related_query_name=None,
                         limit_choices_to=None, parent_link=False, to_field=None,
                         db_constraint=True, **kwargs)

Model:

...
rsft_country = addresses_fields.RsftCountryField(null=True, blank=True)

It prints kwargs two times:

{'null': True, 'blank': True}
{'blank': True, 'null': True, 'related_name': '+', 'on_delete': <function PROTECT at 0x7fa9fa277d00>, 'to': 'addresses.country'}

Why does it do that and how to make it work?

EDIT:

Basically, I just want to provide all the fields by default without having to specify it everytime I define the country field in model.

Advertisement

Answer

The problem is the .deconstruct() method [Django-doc], since that will :

class RsftCountryField(models.ForeignKey):
    def __init__(self, verbose_name=None, **kwargs):
        kwargs['verbose_name'] = verbose_name or 'Krajina'
        to = 'addresses.Country'
        on_delete = kwargs.pop('on_delete',None) or models.PROTECT
        related_name = kwargs.pop('related_name', None) or '+'
        super().__init__(
            to,
            on_delete,
            related_name=related_name,
            related_query_name=None,
            limit_choices_to=None,
            parent_link=False,
            to_field=None,
            db_constraint=True,
            **kwargs
        )

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        kwargs.pop('to', None)
        kwargs.pop('related_query_name', None)
        kwargs.pop('limit_choices_to', None)
        kwargs.pop('parent_link', None)
        kwargs.pop('to_field', None)
        kwargs.pop('db_constraint', None)
        return name, path, args, kwargs

You will need to make new migrations where a RsftCountryField is involved.

Advertisement