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:
JavaScript
x
2
1
TypeError: Couldn't reconstruct field rsft_country on properties.Property: django.db.models.fields.related.ForeignKey.__init__() got multiple values for keyword argument 'to'
2
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.
JavaScript
1
11
11
1
class RsftCountryField(models.ForeignKey):
2
def __init__(self, verbose_name=None, **kwargs):
3
print(kwargs)
4
kwargs['verbose_name'] = verbose_name or 'Krajina'
5
to = 'addresses.Country'
6
on_delete = kwargs.pop('on_delete',None) or models.PROTECT
7
related_name = kwargs.pop('related_name',None) or '+'
8
super().__init__(to, on_delete, related_name=related_name, related_query_name=None,
9
limit_choices_to=None, parent_link=False, to_field=None,
10
db_constraint=True, **kwargs)
11
Model:
JavaScript
1
3
1
2
rsft_country = addresses_fields.RsftCountryField(null=True, blank=True)
3
It prints kwargs
two times:
JavaScript
1
3
1
{'null': True, 'blank': True}
2
{'blank': True, 'null': True, 'related_name': '+', 'on_delete': <function PROTECT at 0x7fa9fa277d00>, 'to': 'addresses.country'}
3
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 :
JavaScript
1
27
27
1
class RsftCountryField(models.ForeignKey):
2
def __init__(self, verbose_name=None, **kwargs):
3
kwargs['verbose_name'] = verbose_name or 'Krajina'
4
to = 'addresses.Country'
5
on_delete = kwargs.pop('on_delete',None) or models.PROTECT
6
related_name = kwargs.pop('related_name', None) or '+'
7
super().__init__(
8
to,
9
on_delete,
10
related_name=related_name,
11
related_query_name=None,
12
limit_choices_to=None,
13
parent_link=False,
14
to_field=None,
15
db_constraint=True,
16
**kwargs
17
)
18
19
def deconstruct(self):
20
name, path, args, kwargs = super().deconstruct()
21
kwargs.pop('to', None)
22
kwargs.pop('related_query_name', None)
23
kwargs.pop('limit_choices_to', None)
24
kwargs.pop('parent_link', None)
25
kwargs.pop('to_field', None)
26
kwargs.pop('db_constraint', None)
27
return name, path, args, kwargs
You will need to make new migrations where a RsftCountryField
is involved.