Currently, the API I'm pulling is as such:
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
. How can I achieve that?
What I have so far:
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()
and 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?
I think you need to add the retrieve
function in the LocationDataView
.
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
...
router = routers.DefaultRouter()
router.register(r'locs', views.LocationListView, 'locs')
router.register(r'locs/<int:pk>', views.LocationDataView, 'locs/data')
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.