我想减少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"https://stackoverflow.com/questions/38315188
复制相似问题