为什么 cached_property 总是更新数据?
Why does cached_property always update the data?
有一个模型,在它的地理位置字段中,latitude
和longitude
被存储为一个字符串,形式为'27 .234234234,53.23423423434'。
此字段由 django-geoposition 提供。感谢他,输入地址非常方便。
我还需要存储真实地址。我不知道这样做是否正确,但我决定使用 geocoder,并将结果存储在 cached_property
class Address(models.Model):
geoposition = GeopositionField(null=True)
city = models.ForeignKey('cities_light.City', null=True)
country = models.ForeignKey('cities_light.Country', null=True)
entrance = models.CharField(null=True, max_length=4, blank=True)
floor = models.CharField(null=True, max_length=4, blank=True)
flat = models.CharField(null=True, max_length=4, blank=True)
@cached_property
def address(self):
g = geocoder.yandex([
str(self.geoposition).split(',')[0],
str(self.geoposition).split(',')[1]
],
method='reverse', lang='ru-RU')
return g.address
def save(self, *args, **kwargs):
if not self.address:
self.address()
super(Address, self).save(*args, **kwargs)
def __str__(self):
if self.address:
return '%s' % str(self.address)
return '%s' % str(self.pk)
但问题是,每次尝试编辑与地址关联的模型时,我都会看到正在计算 属性,甚至在某些情况下,我发现外部服务连接超时.
我无法理解这种行为的原因。
问题是在save ()
方法中,我没有调用address
属性,而是address()
方法,所以没有缓存。
有一个模型,在它的地理位置字段中,latitude
和longitude
被存储为一个字符串,形式为'27 .234234234,53.23423423434'。
此字段由 django-geoposition 提供。感谢他,输入地址非常方便。
我还需要存储真实地址。我不知道这样做是否正确,但我决定使用 geocoder,并将结果存储在 cached_property
class Address(models.Model):
geoposition = GeopositionField(null=True)
city = models.ForeignKey('cities_light.City', null=True)
country = models.ForeignKey('cities_light.Country', null=True)
entrance = models.CharField(null=True, max_length=4, blank=True)
floor = models.CharField(null=True, max_length=4, blank=True)
flat = models.CharField(null=True, max_length=4, blank=True)
@cached_property
def address(self):
g = geocoder.yandex([
str(self.geoposition).split(',')[0],
str(self.geoposition).split(',')[1]
],
method='reverse', lang='ru-RU')
return g.address
def save(self, *args, **kwargs):
if not self.address:
self.address()
super(Address, self).save(*args, **kwargs)
def __str__(self):
if self.address:
return '%s' % str(self.address)
return '%s' % str(self.pk)
但问题是,每次尝试编辑与地址关联的模型时,我都会看到正在计算 属性,甚至在某些情况下,我发现外部服务连接超时.
我无法理解这种行为的原因。
问题是在save ()
方法中,我没有调用address
属性,而是address()
方法,所以没有缓存。