Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django filter parent on base of child

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading