python - 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)
解决方案
我偷看了pycountry
API。对象上的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)。
推荐阅读
- python - 为什么在更多 CPU/内核上的并行化在 Python 中的扩展性如此之差?
- android - 如何在我的 qt 快速应用程序中更改 android 上的默认文本编辑光标?
- ios - Null 不是对象 imagepickerManager.launchCamera
- swift - SwiftUI Tabview - 调用中参数'tab'的参数丢失
- amazon-web-services - 如何获取 ALB 的 ARN
- python - 在 Python Panda 中对部分 DataFrame 进行排序,根据行值返回具有顺序的新列
- wordpress - Wordpress 不显示帖子(Griddist 主题)
- html - 为什么h1的“padding: 2em”等于64px?我觉得应该是16px*2
- flutter - flutter_ffmpeg - 我们可以在录制时修剪视频的一部分吗
- python - 在保持高级别的 tf.keras.fit() API 的同时自定义优化器