我有一个对象函数来检查数据库中是否已存在某个位置。一切正常,直到我添加了检查功能。
models.py
class LocationManager(models.Manager):
def exist(city, state):
if self.queryset.get(city=city, state=state):
return True
return False
def create_new(self, ip_address, city_data):
location = self.model()
if ip_address is not None:
if city_data:
city = city_data['city']
state = city_data['region']
if not self.exist(city=city, state=state):
location.city_data = city_data
location.city = city
location.state = state
location.country = city_data['country_name']
location.latitude = city_data['latitude']
location.longitude = city_data['longitude']
location.save()
return location
else:
return Location.objects.get(city=city, state=state)
class Location(models.Model):
city_data = models.TextField(null=True, blank=True)
city = models.CharField(max_length=120, null=True, blank=True)
state = models.CharField(max_length=2, null=True, blank=True)
country = models.CharField(max_length=20, null=True, blank=True)
latitude = models.FloatField()
longitude = models.FloatField()
objects = LocationManager()
def __str__(self):
return '{}, {}'.format(self.city, self.state)
我遇到错误:
TypeError at /login/
exist() got multiple values for argument 'city'
/home/slim/Desktop/django/locations/models.py在create_new中
if not self.exist_(city=city, state=state):
本地变量:
city 'Mountain View'
city_data {'city': 'Mountain View',
'country_code': 'US',
'country_name': 'United States',
'dma_code': 807,
'latitude': 37.419200000000004,
'longitude': -122.0574,
'postal_code': '94043',
'region': 'CA',
'time_zone': 'America/Los_Angeles'}
ip_address '172.217.4.46'
location <Location: None, None>
self <locations.models.LocationManager object at 0x7f40b3ec6be0>
state 'CA'
答案 0 :(得分:1)
def exist(city, state)
您在self
的定义中缺少exist
。这将导致实例与显式关键字参数city
一起作为city=city
传递。
简化示例:
class Foo:
def bar(a):
print(a)
f = Foo()
f.bar()
# <__main__.Foo object at 0x0000000003698DA0>
f.bar(a='a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() got multiple values for argument 'a'
答案 1 :(得分:1)
您忘记了self
作为第一个参数。
def exist(self, city, state):
# ^^^^