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

Filter queryset based on related object's field value

I have two models:

class PartUse(models.Model):
    ...
    imported = models.BooleanField()


class PartReturn(models.Model):
    partuse = models.ForeignKey(PartUse)
    ...
    imported = models.BooleanField()


class PartUseListView(ListView):
    model = PartUse

    def get_queryset(self):
        if self.request.GET.get('show_imported', None):
            qs = self.model.objects.all()
        else:
            qs = self.model.objects.filter(Exists(PartReturn.objects.filter(
                imported=False, id__in=OuterRef("partreturn"))))
        return qs

I want to filter QuerySet for PartUse to return all PartUse instances that have imported == False for either model. What’s the best way to achieve that?

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

>Solution :

To filter PartUse instances that have imported == False for either model, you can use Django’s Q() objects to perform a query with OR logic.

Try this:

from django.db.models import Q

class PartUseListView(ListView):
    model = PartUse

    def get_queryset(self):
        if self.request.GET.get('show_imported', None):
            qs = self.model.objects.all()
        else:
            qs = self.model.objects.filter(Q(imported=False) | Q(partreturn__imported=False))
        return qs.distinct()

Here, distinct() method is used to avoid duplicate results.

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