我想减少 my_filter_function() 中模板过滤器调用的数量。因为它在模板内的两个 for 循环内使用。请参阅下面的我的代码设置。
class ModelA(models.model):
models.ForeignKey(OtherModel1)
class ModelB(models.model):
models.ForeignKey(OtherModel2)
class ModelC(models.Model):
a = models.ForeignKey(ModelA)
b = models.ForeignKey(ModelB)
def my_views(request):
return render(request, 'my_template.html', {
'a_list': ModelA.objects.all(),
'b_list': ModelB.objects.all(),
})
在我的模板中,我有
{% for a in a_list %}
{% for b in b_list %}
{% with b|my_filter_function:a as my_val %}
Val: {{my_val}}
{% endwith %}
{% endfor %}
{% endfor %}
上面的模板将调用 my_filter_function 过滤函数,我需要找到另一种方法来减少 my_filter_function 函数调用的次数,因为过滤函数现在每个模板访问数据库数千次。
@register.filter
def my_filter_function:(b, a):
z = ModelC.objects.filter(a=a, b=b)
if z.count() > 0:
return "OK"
else:
return "Not OK"
最佳答案
这是一个更快的替代方案。
一次性获取C
中A
和B
的所有id:
z = ModelC.objects.values_list('a_id', 'b_id')
a_related, b_related = zip(*z) # split into a and b ids
将这些传递到您的上下文:
def my_views(request):
return render(request, 'my_template.html', {
'a_list': ModelA.objects.all(),
'b_list': ModelB.objects.all(),
'a_related': a_related,
'b_related': b_related,
})
然后在模板中使用if...in
。现在可以放弃自定义模板过滤器:
{% for a in a_list %}
{% for b in b_list %}
{% if a.id in a_related and b.id in b_related %}
"OK"
{% else %}
"Not ok"
{% endif %}
{% endfor %}
{% endfor %}
这会将过滤器中的所有多个查询替换为一个。
关于python - Django 模型查询调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38315188/