Django ORM如何查询多对多表存在但另一关联表不存在的crlist数据
Django ORM查询实现方案
你需要的是筛选出与指定Cuslistprofile(示例中为id=4的记录)关联的Crlist中,不存在于Crcheck表的记录,两种常见实现方式如下:
方法1:使用exclude + values_list 实现(写法简单,适合小数据量场景)
# 1. 获取Crcheck表中所有出现过的crlist_id集合 existed_crlist_ids = Crcheck.objects.values_list('crlist_id', flat=True) # 2. 取id为4的Cuslistprofile关联的crlist,排除掉已存在于Crcheck的记录 result = Cuslistprofile.objects.get(id=4).crlist.exclude(id__in=existed_crlist_ids)
运行后result即为id为5和7的Crlist对象集合,匹配示例需求。
方法2:使用Exists子查询实现(性能更优,适合大数据量场景)
from django.db.models import Exists, OuterRef # 构造子查询:判断当前Crlist是否在Crcheck表中存在关联记录 crcheck_exists = Crcheck.objects.filter(crlist_id=OuterRef('pk')) # 过滤掉存在Crcheck关联的记录 result = Cuslistprofile.objects.get(id=4).crlist.annotate( has_crcheck=Exists(crcheck_exists) ).filter(has_crcheck=False)
如果不需要限定Cuslistprofile的id,要查询所有多对多中间表中存在的Crlist、排除出现在Crcheck中的记录,写法调整如下:
# 取中间表所有关联的crlist_id all_related_crlist_ids = Cuslistprofile.crlist.through.objects.values_list('crlist_id', flat=True) result = Crlist.objects.filter(id__in=all_related_crlist_ids).exclude( id__in=Crcheck.objects.values_list('crlist_id', flat=True) )
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

