get()接受1个位置参数,但在django中,当试图覆盖save方法时给出了2个位置参数



如何解决这个问题?

from django.db import models
import pycountry
# Create your models here.
class Country(models.Model):
country_name = models.CharField(max_length=50)
code = models.CharField(max_length=3, editable=False)

def save(self, *args, **kwargs):
country_list = []
for country in pycountry.countries:
country_list.append(country.name)
if (self.country_name in country_list):
self.code = pycountry.countries.get(self.country_name).alpha_3
super(Country, self).save(*args, **kwargs)

我偷看了一下pycountryAPI。countries对象上的get方法签名最终看起来像这样:

def get(self, **kw):
...

在Python中意味着它只接受"named"参数。在您的代码中,您将country_name作为位置参数。

我无法从我快速浏览的代码中推断出他们希望你传递什么,但从上下文中我猜它是这样的:

self.code = pycountry.countries.get(name=self.country_name).alpha_3

注意你的参数显式命名的细微差别,而不仅仅是位置传递。

这个错误本身总是有点令人困惑,因为self。Python实例方法总是将self作为隐式位置参数。它告诉你self是唯一有效的位置参数(1),但你同时传递了selfcountry_name的位置参数(2)。