如何在 Django 模板中执行查询过滤 [英] How do I perform query filtering in django templates

查看:34
本文介绍了如何在 Django 模板中执行查询过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 django 模板中执行过滤查询,以在视图中获取一组等效于 python 代码的对象:

I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:

queryset = Modelclass.objects.filter(somekey=foo)

在我的模板中我想做

{% for object in data.somekey_set.FILTER %}

但我似乎不知道如何编写 FILTER.

but I just can't seem to find out how to write FILTER.

推荐答案

你不能这样做,这是设计使然.Django 框架作者打算将表示代码与数据逻辑严格分离.过滤模型是数据逻辑,输出HTML是表现逻辑.

You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.

所以你有几个选择.最简单的方法是进行过滤,然后将结果传递给 render_to_response.或者您可以在模型中编写一个方法,以便您可以说 {% for object in data.filtered_set %}.最后,您可以编写自己的模板标签,但在这种特定情况下,我建议不要这样做.

So you have several options. The easiest is to do the filtering, then pass the result to render_to_response. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}. Finally, you could write your own template tag, although in this specific case I would advise against that.

这篇关于如何在 Django 模板中执行查询过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆