Search code examples
djangodjango-signals

Why does cached_property always update the data?


There is a model, in its geoposition field, latitude and longitude are stored, as a string, in this form '27 .234234234,53.23423423434'.

This field is provided by django-geoposition. Thanks to him it is very convenient to enter the address.

I also need to store the real address. I do not know whether to do this correctly, but I decided to use geocoder, and store the result in 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)

But the problem is that with every attempt to edit a model that is associated with the Address, I see that the property is being computed, and even in some cases I catch connection time out from external services.

I can not understand the reason for this behavior.


Solution

  • The thing was that in the save () method, I did not call the address property, but the address() method, so there was no caching.