如何在Django Rest Framework中使用get_queryset进行过滤?

gkl3eglg  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(127)

目前,我拉取的API是这样的:

http://127.0.0.1:8000/api/locs/data/2

并且输出如下:

{
    "id": 2,
    "date": "2019-01-07",
    "hour": null,
    "measurement": null,
    "location": 6
}

我想要的实际上是通过location值进行过滤,因此从上面的API URL中,我很乐意从location: 2中提取所有数据。我该如何做到这一点?
到目前为止我有:

views.py

class LocationDataView(viewsets.ModelViewSet):
    serializer_class = LocationDataSerializer
    permission_classes = [IsAuthenticated]
    authentication_classes = [TokenAuthentication]

    def get_queryset(self):
        queryset = LocationData.objects.all()
        pk = self.kwargs['pk']
        queryset = queryset.filter(location=pk)

    def perform_create(self, serializer):
        serializer.save()

urls.py

from django.urls import path, include
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'locs', views.LocationListView, 'locs')
router.register(r'locs/data', views.LocationDataView, 'locs/data')

urlpatterns = [
    path('', include(router.urls)),

    path('locs/forecast-data/',
         views.getForecastData, name='forecast-data'),
]

我的问题是,我如何才能访问pk的位置?

esbemjvw

esbemjvw1#

我认为你需要在LocationDataView中添加retrieve函数。

class LocationDataView(viewsets.ModelViewSet):
    ...

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializers = self.get_serializer(instance)
        return Response(serializers.data)

在urls.py

...
router = routers.DefaultRouter()
router.register(r'locs', views.LocationListView, 'locs')
router.register(r'locs/<int:pk>', views.LocationDataView, 'locs/data')
...
yshpjwxd

yshpjwxd2#

不确定你是否还需要答案,也不确定我的解决方案是否好,但我所做的是访问查询函数中的kwargs。
正如在另一个答案中所解释的,你需要一个retrieveget函数来使用请求。我正在使用Django Rest的泛型

class YourClassName(RetrieveAPIView):
        serializer_class = LocationDataSerializer
        permission_classes = [IsAuthenticated]
        authentication_classes = [TokenAuthentication]
        def get_queryset(self):
            return LocationData.objects.filter(location=self.kwargs.get('pk'))
        def retrieve(request, self, *args, **kwargs):
            list = self.get_queryset()
            serializer = self.get_serializer(list, many = True)

相关问题