我想得到一个queryset以及他们的组成员资格,以避免昂贵的额外数据库点击,并使管理模板中的内容更加容易。你知道吗
最初,我尝试预取用户所属的组:
def get_queryset(self):
User.objects.filter(is_active=True).prefetch_related('groups')
但是这样就很难根据组在模板中显示和隐藏内容:
{{ user.groups.all }}
给予
<QuerySet [<Group: Managers>]>
然后我想也许注释用is_manager
和is_head
更好,例如:
from django.db.models import BooleanField, Case, Value, When
def get_queryset(self):
'''Return both active and inactive users for managers
Annotate with is_manager = True/False
'''
query = When(groups__name__in=[MANAGER_GROUP_NAME, ], then=Value(1))
return self.model.objects.all().annotate(
is_manager=Case(
query,
default=Value(0),
output_field=BooleanField()
)
)
它工作正常,但给了我一个错误:
Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'my_site.auth_group.name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
但在模板中很容易使用:
{% if user.is_manager %} Manager {% else %} Normal user {% endif %}
有更简单的方法吗?你知道吗
编辑:
最终查询:
self.model.objects.prefetch_related('groups').all().annotate(
is_manager=Case(
When(
groups__id__exact=1, then=True
), default=False, output_field=BooleanField()
)
).values("pk", "id", "email", "is_manager")
你的方法不错。你知道吗
首先,如果可能的话,考虑使用组id而不是组名来标识
managers
。将显著提高查询性能和拼写错误。你知道吗下面是一个简短的片段,我尝试,并正在为我工作。(在postgres上)。你知道吗
相关问题 更多 >
编程相关推荐