Django: check for value in ManyToMany field in template

梦想的初衷 提交于 2019-12-10 14:49:20

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/8442010/django-check-for-value-in-manytomany-field-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!