[Answered ]-Django filtering relation in ListView

1👍

You can use prefetch_related with a Prefetch that uses a custom filtered queryset like this:

from django.db.models import Prefetch, Q


def get_queryset(self):
    if self.request.user.is_admin:
        return TaskGroup.objects.all()

    return TaskGroup.objects.prefetch_related(
        Prefetch(
            'task_set',
            queryset=Task.objects.filter(Q(completed=False) | Q(completed_by=self.request.user))
        )
    )

This will get all the TaskGroups with the related Taskss (in task_set) filtered by those that are not yet completed or are completed by the current user.

Leave a comment