I've got following situation: I have got Project record with several Reviews and user can vote for every review. And I have encountered problem that I have no idea how to display that user already voted and which was his choice.

First of all I've managed to get plain values of review ids and vote values for current user.a

review_votes = UserReviewVote.objects.filter(Q(review_id__in=Review.objects.filter(project=project) .values_list('id', flat=True)) & Q(user=request.user)).values_list('review_id', 'vote')

review_votes = dict((x, y) for x, y in review_votes)  

values_list return tuple of tuples where you've got values for each row. I've converted it to dictionary where key is the review id and value is upvote or downvote casted by user.

I have had no idea how could I manage to get keys from the dict or check that this dict has my value. It could be easy if I've got fixed values, because of Django template engine lookup. But this part of my application is dynamic.

To go over it I've create custom tamplate tag. First I have to create template tags directory like following: project_package\templatetags where I've got __init__.py and project_package_extras.py files with following template tag code:

from django.template.defaulttags import register

@register.filter
def get_dict_item(dictionary, key):  
    try:
        return dictionary.get(key)
    except:
        return None

That's all. Now I have to add following line in my template to load this tag: {% load upgrademystartup_extras %} and I could use template tag like following:

{{ review_votes|get_dict_item: review.id }}

or in if condition when I want to check value of the vote:

{% if review_votes|get_dict_item:review.id == 1 %}

That's all. I think this code has good performance, because other variants is adding method to the model and it could cause too many database queries. But it's optimal to use dict lookup, because as I know about dictionary data structure it uses hash algorithms and really fast with unique values.