Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: check for value in ManyToMany field in template

I have the following model in my Django app:

class Group(models.model):
    name=models.CharField(max_length=30)
    users=Models.ManyToManyField(User)

In my template, I want to display each group, along with a button underneath each. If the user is already in the group, I want to display a "Leave Group" button, and if they are not already in the group, I want to display a "Join Group" button.

What is the most efficient way to determine whether the currently logged in user is in each group? I would rather not query the db for each group that is displayed, which it seems would happen if I just did the following.

{% if user in group.users.all %}

Thanks.

like image 537
rolling stone Avatar asked Dec 09 '11 06:12

rolling stone


1 Answers

In your view, create a set of group IDs that this user is a part of. One of the main uses of set is membership testing.

user_group_set = set(current_user.group_set.values_list('id',flat=true))

Then pass it into your template context:

return render_to_response('template.html',{'user_group_set':user_group_set})

In your template, for each group use:

{% if group.id in user_group_set %}
like image 180
Elliott Avatar answered Nov 02 '22 17:11

Elliott