[Answered ]-How to expose a filtered reverse relationship in Django REST API framework?

2👍

There are a few ways -> from more general to more specific.

The general one: Alter the TaskManager to always return Tasks with is_deleted = False.

class TaskManager(models.Manager):
    def get_queryset(self):
        return super(self.__class__, self).get_queryset().filter(is_deleted=False)


class Task(models.Model):
    # ...
    objects = TaskManager()

The specific one: use prefetch_related with custom Prefetch object.

person = Person.objects.filter(is_deleted=False, pk=person_id) \
            .prefetch_related(
                Prefetch('task_set', queryset=Task.objects.filter(is_deleted=False))
            ) \
            .get()

Of course you can create a more intermediate solution by moving this method into a PersonManager class, so you can make something like:

person = Person.objects.get_person_without_deleted_tasks(pk=person_id)
👤Todor

Leave a comment