将原始SQLWHERE子句添加到django查询集
是否可以向django查询集添加额外的原始sql子句? 最好使用RawSQL子句将其转换为普通查询集。 它应该是一个普通的queryset,而不是rawqueryset,因为我想在django管理中使用它 在我的特殊情况下,我想添加一个额外的exists where子句:将原始SQLWHERE子句添加到django查询集,django,django-queryset,Django,Django Queryset,是否可以向django查询集添加额外的原始sql子句? 最好使用RawSQL子句将其转换为普通查询集。 它应该是一个普通的queryset,而不是rawqueryset,因为我想在django管理中使用它 在我的特殊情况下,我想添加一个额外的exists where子句: and exists ( select 1 from ... ) 在我的具体案例中,我有两个模型:客户模型和订阅模型。订阅具有开始日期字段和可选的结束日期字段 我想与今天有当前订阅的所有客户建立一个查询集。与此S
and exists (
select 1
from ...
)
在我的具体案例中,我有两个模型:客户模型和订阅模型。订阅具有开始日期字段和可选的结束日期字段
我想与今天有当前订阅的所有客户建立一个查询集。与此SQL查询类似:
select *
from customers_customer c
where exists (
select 1
from subscriptions_subscription sc
where sc.customer_id = c.id
and sc.start < current_date
and (sc.end is null or sc.end > current_date)
)
我没能从中找出一个疑问。
我到达的最好的地方是:
cs = Customer.objects.annotate(num_subscriptions=RawSQL(
'''
select count(sc.id)
from subscriptions_customersubscription sc
where sc.customer_id = customers_customer.id
and sc.start < current_date
and (sc.end is null or sc.end > current_date)
''', []
))
但此查询的性能不如where exists的SQL查询。不回答您的问题,但您可以像这样查询客户:
from django.db.models import Q
Customer.objects.filter(
Q(subscription__start__lt=current_date),
Q(subscription__end=None) | Q (subscription__end__gt=current_date)
).distinct()
你能发布你的模型吗?您正在尝试手动联接表,像Customer.objects.filtersubscriptions\uuuuu start\uuuu lt=current\u date等那样自然联接有问题吗?好的,自然联接可以正常工作,并且完全符合我的要求。。。我只是没有想到……我没有想到简单的解决办法。虽然这并没有回答问题,但它解决了我的问题:向上投票