Skip to main content
 首页 » 编程设计

python之获取用户列表以及组成员身份

2025年01月19日9zlslch

我想获得一个查询集及其组成员身份,以避免昂贵的额外数据库命中,并使模板中的管理变得更加容易。

最初我尝试预取用户所属的组:

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 而不是群组名称来识别经理。将显着提高查询性能和拼写相关的错误。

以下是我尝试过并为我工作的快速片段。 (在 postgres 上)。

User.objects.prefetch_related("groups").annotate( 
    is_super=Case( 
        When( 
            groups__id__in=[1, 2,3 ], then=1 
        ), default=0, output_field=IntegerField() 
    ) 
).order_by("id").values_list("id", "username", "is_super")