如何合并来自两个模型的两个过滤器?

时间:2019-06-22 14:03:41

标签: django django-views

如何组合来自两个模型的两个过滤器?

必须作为AND(&)

Credit.objects.filter(id__in=CreditPayment.objects.filter(security='Deposit - deposit').values('credit__id').distinct(), bank__id=1))

Credit.objects.filter(id__in=Condition.objects.filter(purpose=3).values('credit__id').distinct(), bank__id=1))

2 个答案:

答案 0 :(得分:2)

您可以将django Q与&

一起使用
from django.db.models import Q
Credit.objects.filter(Q(id__in=CreditPayment.objects.filter(security='Deposit - deposit').values('credit__id').distinct()) & Q(id__in=Condition.objects.filter(purpose=3).values('credit__id').distinct()), bank__id=1))

答案 1 :(得分:1)

鉴于我的理解正确,您可以在加入Condition模型的两个过滤器语句中执行此操作,例如:

Credit.objects.filter(
    bank__id=1,
    condition__security='Deposit - deposit'
).filter(
    condition__purpose=3
).distinct()

这将产生一个查询,例如:

SELECT DISTINCT credit.*
FROM credit
INNER JOIN condition ON credit.id = condition.credit_id
INNER JOIN condition T3 ON credit.id = T3.credit_id
WHERE credit.bank_id = 1
  AND condition.security = Deposit - deposit
  AND T3.purpose = 3