首页 > 解决方案 > get() 接受 1 个位置参数,但在尝试覆盖 django 中的保存方法时给出了 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)

标签: pythondjango-models

解决方案


我偷看了pycountryAPI。对象上的get方法签名countries最终如下所示:

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

在 Python 中,这意味着它只接受“命名”参数。在您的代码中,您将country_name作为位置参数给出。

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

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

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

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


推荐阅读