英文:
Django filter parent on base of child
问题
我有一个发票模型:
class Invoice(models.Model):
name = models.ForeignKey('Patient', on_delete=models.CASCADE)
我还有另一个发票金额模型,它有一个发票的外键:
class InvoiceAmount(models.Model):
invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE)
amount = models.IntegerField(default=0)
is_paid = models.BooleanField(default=False)
我想获取已支付的发票金额的发票。
我正在使用以下查询,但它不起作用:
Invoice.objects.annotate(all_paid=Exists(InvoiceAmount.objects.filter(is_paid=True, id=OuterRef('pk')))).filter(all_paid=True)
英文:
i have invoice model
class Invoice(models.Model):
name = models.ForeignKey('Patient', on_delete=models.CASCADE)
i have another invoice amount model which have FK of invoice
class InvoiceAmount(models.Model):
invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE)
amount = models.IntegerField(default=0)
is_paid = models.BooleanField(default=False)
i want to get invoices which have is_paid = True invoice amounts
i am using this query but it's not working
Invoice.objects.annotate(all_paid=Exists(InvoiceAmount.objects.filter(is_paid=True, id=OuterRef('pk')))).filter(all_paid=True)
答案1
得分: 1
你可以检查是否存在is_paid=False
的InvoiceAmount
,所以:
from django.db.models import Exists, OuterRef, Q
Invoice.objects.annotate(
all_paid=~Exists(
InvoiceAmount.objects.filter(~Q(is_paid=True), invoice_id=OuterRef('pk'))
)
).filter(all_paid=True)
英文:
You can check if there are no InvoiceAmount
s with is_paid=False
, so:
<pre><code>from django.db.models import Exists, OuterRef, Q
Invoice.objects.annotate(
all_paid=<b>~</b>Exists(
InvoiceAmount.objects.filter(<b>~Q(is_paid=True)</b>, <b>invoice_id</b>=OuterRef('pk'))
)
).filter(all_paid=True)</code></pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论