[Django]-Best practice for getting items filtered by owner in RESTfull resources

3👍

I think you can go both ways, but you have to think about a couple of things.

You can do a filter for the “QUERY_PARAMS” and when is “self” you just query for the owner request.user or the name of the user, but of course, there can’t be a user named “self” for username or you will have a edge case

If you decide to create your own endPoint for this, you can do it this way, create as many filters as you need like:

from rest_framework import filters

class OwnerFilterBackend(filters.BaseFilterBackend):
    """
    Filter that request user view his own objects
    """
    def filter_queryset(self, request, queryset, view):
        """
        :param request: HTTP Request
        :param queryset: View QuerySet
        :param view: View Instance
        :return: QuerySet filter by the user request as the owner
        """
        return queryset.filter(owner=request.user)

And then just add the filter to your new api view:

class PlannedMealList(generics.ListCreateAPIView):
    serializer_class = PlannedMealSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    filter_backends = (OwnerFilterBackend,)
    ....
    ....

You can apply several filter, like for the date or ordering and it will help to keep it DRY

A example applying many filters

class PlannedMealList(generics.ListCreateAPIView):
        serializer_class = PlannedMealSerializer
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
        filter_backends = (OwnerFilterBackend, filters.DjangoFilterBackend, filters.OrderingFilter)
        filter_class = MyFilterClass
        ....
        ....

If you have further questions, I can help you 😉

Leave a comment