About select_related () caching

I am making a select_related () request to prevent a malicious database. In my model, I:

class Item(models.Model)
    user = models.ForeignKey(User, related_name='items')
    name = models.CharField(max_length=255)
    region = models.ForeignKey(Region, null = True, blank = True) #django-cities
    country = models.ForeignKey(Country, null = True, blank = True) #django-cities

    def get_ubicacion_name(self):
        if self.region:
             return self.region
        else:
             return self.country

class Activity(models.Model)
    date = models.DateField()
    item = models.ForeignKey(Item, related_name='items')

In my opinion:

ax = Activity.objects.select_related('item','item__region','item__country').all()[:40]

In my template:

{% for a in ax %}
    {{ a.date }} - {{ a.get_ubicacion_name }}
{% endfor %}

the debug toolbar displays 43 queries in 53.87msbecause it clicks self.country, so select_related('item','item_region','item_country')def does not work for this?

In the shell:

>>> ac = ax[0]
>>> dir(ac)
...... '_item_cache', .......
>>> dir(ac.item)
...... '_country_cache','_region_cache',.......

thank.

+3
source share
2 answers

That should work. Can you try it in a shell? Get the query request axin the same way as in the view, then examine the first element with dir:

>>> ac = ax[0]
>>> dir(ac) 

, , - _item_cache, Django ForeignKey. , dir(ac.item), _region_cache _country_cache. , , , .

0

, , :

class City(models.Model):
# snip
region = models.ForeignKey(Region)
# snip

def __unicode__(self):
    return "%s, %s" % (self.name, self.region)

get_ubicacion_name(), , City.__unicode__(), ( ) .

select_related :

ax = Activity.objects.select_related(
    'item','item__region__city__country','item__country'
).all()[:40]

, , .

0

Source: https://habr.com/ru/post/1788208/


All Articles