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

查看:156
本文介绍了如何在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 。或者您可以在模型中编写一个方法,以便您可以在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天全站免登陆