Is it possible, in a django template, to check if an object is contained in a list

Posted by AlexH on Stack Overflow See other posts from Stack Overflow or by AlexH
Published on 2010-03-11T18:06:41Z Indexed on 2010/03/11 18:09 UTC
Read the original article Hit count: 243

Filed under:

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?

© Stack Overflow or respective owner

Related posts about django