Filter queryset based on related object's field value

Question:

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?

Asked By: Viktor

||

Answers:

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.

Answered By: Sunderam Dubey