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.
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With