Brenden
Brenden

Reputation: 8764

Marking favorites in django object set

I have a table called Tip and table called FavoritedTips. Users favorite Tips in my app and the tip ID and user ID are added to the favoritedTips table.

class FavoritedTip(models.Model):
    tip = models.ForeignKey(Tip)
    user = models.ForeignKey(User)

I now need to put a star next to the tip when the tips appear in the list. But of course tips = Tip.objects.filter(list=list) doesn't have a tip.favoritedtip column.

What's the easiest thing to do in my template to know which tip has been favorited?

Upvotes: 0

Views: 699

Answers (2)

Stan
Stan

Reputation: 8976

I presume you want to display a list of tips and for each one you need to know if this is a favorite of the current user.

You can do it with a custom templatetag if you really want to do that at the template level, but you'd better build your data structure in the view :

tips = Tips.objects.filter(my_filters)
user_favorite_tips = request.user.favoritedtip_set.values_list('pk', flat=True)
tips = [{'tip': tip, 
         'is_favorite': tip.pk in user_favorite_tips and True or False}
         for tip in tips]

And then in your template :

<ul>
{% for tip in tips %}
    <li>{{ tip.tip.as_html }} 
        {% if tip.is_favorite %} <img src="star.png" />{% endif %}</li>
{% endfor %}
</ul>

Upvotes: 1

Elliott
Elliott

Reputation: 1376

You can do it with 2 queries by doing the following:

1: Create a set containing the IDs of the tips that the current user has favorited

favorite_set = set(Tip.objects.filter(favoritedtip_set__user__exact=currentUser).values_list('id',flat=True))

2: (you probably want to do this in the template)For each Tip object, check if that object's ID is in favorite_set. If it is, put a star next to it.

Upvotes: 0

Related Questions