Django如何构造Q对象查询用户同时拥有两组权限中各至少一项
问题根因
你之前构造的Q对象逻辑是要求单条权限记录同时满足两组OR条件,但每条Permission记录只能对应一个实体的权限,不可能同时属于两个完全独立的权限组,所以查询返回False。
解决方案
方案1:两次独立exists查询(推荐)
该方案逻辑最清晰,性能开销极低,适合绝大多数场景:
# 定义两组权限校验条件 q_branch1 = ( Q(content_type=ContentType.objects.get_for_model(Foo), object_id=676) | Q(content_type=ContentType.objects.get_for_model(Bar), object_id=634) | Q(content_type=ContentType.objects.get_for_model(Wibble), object_id=1) ) q_branch2 = ( Q(content_type=ContentType.objects.get_for_model(Foo), object_id=2) | Q(content_type=ContentType.objects.get_for_model(Bar), object_id=633) | Q(content_type=ContentType.objects.get_for_model(Wibble), object_id=2) ) # 分别校验两个分支都存在对应权限 user_perm_qs = Permission.objects.filter(user=your_target_user) has_required_perm = user_perm_qs.filter(q_branch1).exists() and user_perm_qs.filter(q_branch2).exists()
方案2:单次聚合查询
如果需要合并为一次数据库请求,可以用分组聚合判断同时匹配两个分支的记录数是否达标:
from django.db.models import Count, Q has_required_perm = Permission.objects.filter( user=your_target_user, q_branch1 | q_branch2 ).values('user').annotate( # 统计匹配的独立权限记录数 matched_branches = Count('id', distinct=True) # 至少匹配2个分支的权限才符合要求 ).filter(matched_branches__gte=2).exists()
注意:该方案需要保证两组条件没有重叠,也就是不会出现同一条权限记录同时满足q_branch1和q_branch2的情况,你的场景下两个分支的实体完全独立,符合该前提。
内容的提问来源于stack exchange,提问作者David Downes
相关产品推荐
相关产品推荐

