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)
>Solution :
You can check if there are no InvoiceAmounts with is_paid=False, so:
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)