在django模板中,是否可以检查对象是否包含在列表中 [英] Is it possible, in a django template, to check if an object is contained in a list
问题描述
我正在做一个用户输入内容的网站,然后其他用户可以投票决定是否他们喜欢的东西不是。我知道这不是那么的新奇,但这是一个很好的项目,可以学习一大堆工具。
我有一个多对多表来存储谁喜欢或不喜欢什么。在我提交页面之前,我会拉出当前用户的所有喜好和不喜欢,以及我将在页面上显示的内容。
当我渲染页面,我将通过我将要显示的东西列表,并一次打印出一个。我想向用户展示他们喜欢的东西,以及他们没有的东西。
所以在我的django模板中,我有一个名为entry的对象。我也有两个被称为喜欢和不喜欢的对象列表。有没有办法确定条目是否是我的django模板中的任一列表的成员。
我想我正在寻找的是一个过滤器,我可以说像
{%if entry | in:likes%}
或
{%if likes | contains:entry%}
我知道我可以添加一个方法到我的模型,并单独检查每个条目,但似乎这将是数据库密集的。
有没有更好的方法来考虑这个问题?
here 。非常类似于他们在主干上使用的内容。 将其保存为smart_if.py在您的一个应用程序的模板标签文件夹中,然后一个简单的{%load smart_if%}用新的智能代替了无聊的内置Django {%if%}模板。
I'm very new to django, about a week into it.
I'm making a site where users enter stuff, then other users can vote on whether they like the stuff or not. I know it's not so novel, but it's a good project to learn a bunch of tools.
I have a many-to-many table for storing who likes or dislikes what. Before I render the page, I pull out all the likes and dislikes for the current user, along with the stuff I'm going to show on the page.
When I render the page, I go through the list of stuff I'm going to show and print them out one at a time. I want to show the user which stuff they liked, and which they didn't.
So in my django template, I have an object called entry. I also have two lists of objects called likes and dislikes. Is there any way to determine if entry is a member of either list, inside my django template.
I think what I'm looking for is a filter where I can say something like
{% if entry|in:likes %}
or
{% if likes|contains:entry %}
I know I could add a method to my model and check for each entry individually, but that seems like it would be database intensive.
Is there a better way to think about this problem?
Go here. Very similar to what they're using on trunk. "Save this as smart_if.py in the templatetags folder of one of your apps. Then a simple {% load smart_if %} replaces the boring built-in Django {% if %} template with the new smart one."
这篇关于在django模板中,是否可以检查对象是否包含在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!