Reputation: 113
I have the following model and manager.
class StateManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
class State(models.Model):
class Meta:
verbose_name = "State"
verbose_name_plural = "States"
permissions = (
('access_state', 'Can access States'),
)
COUNTRIES = (
('India', 'India'),
('USA', 'USA'),
('Thailand', 'Thailand'),
)
# Managers
objects = StateManager()
# Database fields
name = models.CharField(
'Name',
max_length=100,
unique=True,
help_text='''
100 chars max
'''
)
code = models.CharField(
'Code',
max_length=10,
unique=True,
help_text='''
10 chars max
''',
null=True, blank=True
)
country = models.CharField(
max_length=50,
default="India",
choices=COUNTRIES,
blank=False,
null=False
)
def __str__(self):
return self.name
def natural_key(self):
return self.name
My fixture file is given below
[
{
"model": "parties.state",
"fields": {
"name": "Andaman and Nicobar",
"code": "AN",
"country": "India"
}
},
{
"model": "parties.state",
"fields": {
"name": "Andhra Pradesh",
"code": "AP",
"country": "India"
}
},
]
I've earlier dumped the data to a fixture file. But when I am trying to load the fixture now, I am getting the following error ...
Traceback (most recent call last):
.....
.....
TypeError: get_by_natural_key() takes 2 positional arguments but 20 were given
.....
.....
File "/home/parijath/Projects/virtualenv/django18/lib/python3.4/site-packages/django/core/serializers/base.py", line 195, in build_instance
obj.pk = Model._default_manager.db_manager(db).get_by_natural_key(*natural_key).pk
django.core.serializers.base.DeserializationError: Problem installing fixture '/home/parijath/Projects/django_projects/webportal18_multipleapps/parties/fixtures/states.json': get_by_natural_key() takes 2 positional arguments but 20 were given
Upvotes: 3
Views: 512
Reputation: 309089
The natural_key
method should return a tuple, not a string.
def natural_key(self):
return (self.name,)
If natural_key
is a string "Andaman and Nicobar"
instead of a tuple ('Andaman and Nicobar',)
then *natural_key
will unpack each of the 19 characters in the string as a separate argument. Along with self
, that gives you 20 arguments from your error message.
Upvotes: 4