问题描述
我的Django应用程序中具有以下模型:
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 %}
谢谢。
推荐答案
在您的视图中,创建该用户所属的组ID的组
。 set
的主要用途之一是成员资格测试。
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 %}
这篇关于Django:在模板的ManyToMany字段中检查值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!