rolling stone
rolling stone

Reputation: 13016

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.

Upvotes: 7

Views: 2122

Answers (1)

Elliott
Elliott

Reputation: 1376

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 %}

Upvotes: 8

Related Questions