Django根据子项筛选父项

huangapple go评论60阅读模式
英文:

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=FalseInvoiceAmount,所以:

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 InvoiceAmounts 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>

huangapple
  • 本文由 发表于 2023年7月27日 17:00:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定