Django 5.0.2:TypeError:获取切片后无法过滤查询

问题描述 投票:0回答:1

为什么这不起作用? 我收到错误“获取切片后无法过滤查询”。 我可以做什么来解决这个问题?

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

我需要这样的东西:

SELECT * FROM logbook WHERE organizationID='1111' ORDER_BY created LIMIT 10;
django django-views
1个回答
0
投票

这是由于

filterset_fields
。此类过滤将在 .get_queryset(…)
 
[drf-doc]
之后发生,但由于您在
get_queryset
 中切片,因此无法进行额外过滤。

您可以在

.paginate_queryset(…)

 中进行切片:

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]
    
© www.soinside.com 2019 - 2024. All rights reserved.