我需要使用Django ORM构建一个查询,这个查询在SQL中是这样的:
select * from A where id not in (select a_id from B where ... )
我试着使用这样的代码:
ids = B.objects.filter(...)
a_objects = A.object.exclude(id__in=Subquery(ids.values('a__id'))).all()
问题是,与嵌套的select Django不同,Django生成的查询类似于
select * from A where id not in (1, 2, 3, 4, 5 ....)
when子句显式列出应排除的所有is,使结果sql在打印到日志中时不可读。是否可以添加此查询,从而使用嵌套select?
发布于 2022-10-25 08:08:09
所以我看到你的目标是从B得到所有没有外键关系的A,如果我是对的,你可以用反向查找来做。
所以,当你定义这样的模型时:
class A:
pass
class B:
a = ForeignKey(to=a, related_name='bs')
您可以这样过滤它:
A.objects.filter(bs__isnull=True)
另外,如果您不定义related_name
,它将默认为b_set
,因此您将能够使用A.objects.filter(b_set__isnull=True)
发布于 2022-10-27 00:24:55
要在B上做一个过滤器,你可以
ids = B.objects.filter(x=x).values_list('id',flat=true)
您得到了一个ids列表,然后
a_objects = A.object.exclude(id__in=ids)
如前所述,如果有关系的话
发布于 2022-10-29 18:14:38
您不需要做任何特别的事情,只需在过滤器中直接使用queryset即可。
ids = B.objects.filter(...)
a_objects = A.object.exclude(id__in=ids).all()
# that should generate the subquery statement
select * from A where NOT (id in (select a_id from B where ... ))
https://stackoverflow.com/questions/74085862
复制相似问题