Django 5.0.2: TypeError: Cannot filter a query once a slice has been taken

Why is this not working? I get the error "Cannot filter a query once a slice has been taken." What can I do to solve this?

class LogbookLastViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = LogbookSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['organizationID']
    
    def get_queryset(self):
        queryset = Logbook.objects.filter(organizationID='1111').order_by('-created')[:10]
        return queryset

I need something like this:

SELECT * FROM logbook WHERE organizationID='1111' ORDER_BY created LIMIT 10;

This is due to the filterset_fields. Such filtering will happen after the .get_queryset(…) [drf-doc], but since you slice in the get_queryset, additional filtering is not possible.

You can do the slicing in the .paginate_queryset(…) instead:

class LogbookLastViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = LogbookSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['organizationID']
    queryset = Logbook.objects.all()

    def paginate_queryset(self, queryset):
        return queryset[:10]
Back to Top