如何组合来自两个模型的两个过滤器?
必须作为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))
答案 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