Django基于子对象过滤父对象

k4emjkb1  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(93)

我有发票型号

class Invoice(models.Model):
    name                         = models.ForeignKey('Patient', on_delete=models.CASCADE)

字符串
我有另一个发票金额模型,其中有发票FK

class InvoiceAmount(models.Model):
    invoice                         = models.ForeignKey('Invoice', on_delete=models.CASCADE)
    amount                          = models.IntegerField(default=0)
    is_paid                         = models.BooleanField(default=False)


我想获取具有is_paid =真实发票金额的发票
我正在使用此查询,但它不工作

Invoice.objects.annotate(all_paid=Exists(InvoiceAmount.objects.filter(is_paid=True, id=OuterRef('pk')))).filter(all_paid=True)

bprjcwpo

bprjcwpo1#

你可以检查是否有InvoiceAmount s与is_paid=False,所以:

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)

字符串

相关问题