[英]How to filter using get_queryset in Django Rest Framework?
Currently, the API I'm pulling is as such:目前,我正在提取的 API 是这样的:
http://127.0.0.1:8000/api/locs/data/2
and the output is as such:输出如下:
{
"id": 2,
"date": "2019-01-07",
"hour": null,
"measurement": null,
"location": 6
}
What I want is actually filtering by the location
value, so from the API url above, I would love to pull all the data that is from location: 2
.我想要的实际上是按
location
值过滤,所以从上面的 API url 中,我很想提取来自location: 2
的所有数据。 How can I achieve that?我怎样才能做到这一点?
What I have so far:到目前为止我所拥有的:
views.py视图.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()
and urls.py和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'),
]
My question is that, how can I access the pk
for the location?我的问题是,如何访问该位置的
pk
?
I think you need to add the retrieve
function in the LocationDataView
.我认为您需要在
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)
And in urls.py在 urls.py
...
router = routers.DefaultRouter()
router.register(r'locs', views.LocationListView, 'locs')
router.register(r'locs/<int:pk>', views.LocationDataView, 'locs/data')
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.