Django templatetags似乎使prefetch_related无用

时间:2017-11-10 19:38:50

标签: django prefetch templatetags

当我将基于模板标记(" provinceonly")的过滤器添加到我的Django模板时,debug-toolbar表示数据库被点击115次而不是之前的5次。

这是一个众所周知的问题吗?我不能'找到一种方法来正确预取所需信息以减少命中数。我有什么可以做的吗?

模板:

{% for country in allcountries %}
    {% for province in country.fkcountrysecondaries.all|provinceonly %}
        {{ province.basicname }}
            {% for populatedplace in province.fkprovince.fkprovincesecondaries.all %}
                    {{ populatedplace.basicname }}
            {% endfor %}
    {% endfor %}
{% endfor %}

模板标签:

from django import template
register = template.Library()
@register.filter
def provinceonly(thelist):
    return thelist.filter(type="province")

查看:

def indexconsistencycheck(request):
    allcountries = NaturalEarthCountry.objects.all().prefetch_related('fkcountrysecondaries__fkprovince__fkprovincesecondaries').select_related('fkcountrymain')

型号:

class NaturalEarthAll(models.Model):
    fkcountry = models.OneToOneField(NaturalEarthCountry, blank=True, null=True, on_delete=models.SET_NULL, related_name="fkcountrymain")
    fkprovince = models.OneToOneField(NaturalEarthProvince, blank=True, null=True, on_delete=models.SET_NULL, related_name="fkprovincemain")
    fktouristicarea = models.ForeignKey(TouristicArea, blank=True, null=True, related_name='relatednatmerged', on_delete=models.SET_NULL)
    fkcountrysecondary = models.ForeignKey(NaturalEarthCountry, blank=True, null=True, on_delete=models.SET_NULL, related_name="fkcountrysecondaries")
    fkprovincesecondary = models.ForeignKey(NaturalEarthProvince, blank=True, null=True, on_delete=models.SET_NULL, related_name="fkprovincesecondaries")

1 个答案:

答案 0 :(得分:0)

正如Sachin所解释的,templatetag会生成一个新的查询集,它会丢失预取的数据。因此,我必须直接在我需要过滤(省)而不是前一个(国家)的模型上执行主查询集,然后按国家/地区重新分组结果。

非常感谢

视图:

allprovinces_list = NaturalEarthMerged.objects.filter(type="province").order_by('fkcountrysecondary__name').prefetch_related('fkprovince__fkprovincesecondaries', 'fkcountrysecondary__fkcountrymain').select_related('fkcountrysecondary')

模板:

{% regroup allprovinces by fkcountrysecondary.name as countrylist %}
{% for listofprovinces in countrylist %}
    {{ listofprovinces.grouper }}
    {% for province in listofprovinces.list %}
        {{ province.basicname }}
        {% for populatedplace in province.fkprovince.fkprovincesecondaries.all %}
            {{ populatedplace.basicname }}
        {% endfor %}
    {% endfor %}
{% endfor %}