I am building a map with different station location. The stations belong to different fields. I have to show all station and, I have all station of a field.
At some point my api is called
"""Markers API URL Configuration."""
# Maps with Django (2)
# https://www.paulox.net/2021/07/19/maps-with-django-part-2-geodjango-postgis-and-leaflet/
from rest_framework import routers
from map.viewsets import MarkerViewSet
router = routers.DefaultRouter()
router.register(r"map", MarkerViewSet)
urlpatterns = router.urls
then the MarkerViewSet is called (viewsets.py)
class MarkerViewSet(viewsets.ReadOnlyModelViewSet):
"""Marker view set."""
#print(self.kwargs.get('idfield'))
bbox_filter_field = "location"
filter_backends = (filters.InBBoxFilter,)
queryset = Stations.objects.filter(station_active=1, map=1)
serializer_class = StationsSerializer
def get_queryset(self, **kwargs):
#field_id = self.kwargs['idfield']
#print("pp:", self.kwargs)
return Stations.objects.filter(fields_id_field=1)
The code above works, but it only show the markers of the field 1
If I change this to 2
return Stations.objects.filter(fields_id_field=2)
It show all station of the field with the id 2
My url is as the follwoing http://127.0.0.1:8080/map/ to print all stations of all fields. If I want to have the stations of the field 1, my url will be
http://127.0.0.1:8080/map/1/field
and for the field 2 and 4
http://127.0.0.1:8080/map/2/field
http://127.0.0.1:8080/map/4/field
My problem, I can not not and I do not know of to get the id 1,2,4 or another form my url
this does not work
#field_id = self.kwargs['idfield']
#print("pp:", self.kwargs)
Here is my map/urls.py an my project urls.py
Should I try to get the id of the field from the viewsets.py or how would you suggest me to archive my goal?
EDIT: Here is my views.py. Here I can get idfield Would it have a way to pass it my viewsets.py?
Args I believe you API urls should be as follows
/maps/--> returns a list of objects/maps/<id>/--> returns a single objectIf you do this you should be able to get results according to the given
id(if primary key) without doing anything in your view.viewsetsautomatically returns an object based on thelookup field. If it is not a primary key you can set different lookup field.Kwargs in kwargs your URL should be as
/maps/?idfield=<id>, then you will be able to do the followings.kwargsfrom GET request can be obtained as below