0

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?

pierrot10
  • 1
  • 3
  • You should pass a `?` after the `/` to get the parameter. `http://127.0.0.1:8080/map/2/?some_field=field` then `request.GET.get("some_field", None)`. – Elias Prado Aug 19 '22 at 22:38

2 Answers2

0

Args I believe you API urls should be as follows

  1. /maps/ --> returns a list of objects
  2. /maps/<id>/ --> returns a single object

If you do this you should be able to get results according to the given id (if primary key) without doing anything in your view. viewsets automatically returns an object based on the lookup 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.

kwargs from GET request can be obtained as below

request.GET.get("idfield")
Tasawer Nawaz
  • 927
  • 8
  • 19
  • Hello, thanks for your reply, but how can I insert the request.GET.get()? I tried to modified [this]{https://github.com/ecosensors/Django/blob/main/EcoSensors/console/map/viewsets.py#L20) but I am not sure where should I declare request – pierrot10 Aug 18 '22 at 19:47
  • please check my updated answer, i hope this will help you. – Tasawer Nawaz Aug 22 '22 at 09:22
0

I beleive that your proposition only works in views.py as it start with

def field(request, idfield):
    request.GET.get("idfield")

isn't?

I am working with a viewsets.py starting with

class MarkerViewSet(viewsets.ReadOnlyModelViewSet):
    """Marker view set."""
    bbox_filter_field = "location"
    filter_backends = (filters.InBBoxFilter,)
    queryset = Stations.objects.filter(station_active=1, map=1)
    serializer_class = StationsSerializer
    """
    def get_tags(self):
        return Stations.objects.filter(fields_id_field=1)
    """
    def get_queryset(self):
        #field_id = self.kwargs['idfield']
        #print("ppp:", self.kwargs['idfield'])
        return Stations.objects.filter(fields_id_field=1)

I do know where your proposition could be added.

However, I think I am getting close to the solution, but I still get error.

I hope you can help me

First, in my map.js file. I added

async function load_markers() {
    const markers_url = `/api/map/1/`; // LOOK AT THIS LINE
    console.log("markers_url: ",markers_url);
    const response = await fetch(markers_url);
    //console.log("response: ",response);
    const geojson = await response.json();
    console.log("geojson: ",geojson);
    return geojson;
}

In my urls.py file, I changed to

path("api/<int:idf>/", include("map.api")),

which will redirect to the api.py file. I think, all is correct until this point, isn't?

In my api.py file, I have tried serveral things getting inspirated from the django-rest-framework - router page

router = routers.DefaultRouter()
#router.register(r"map", MarkerViewSet) #INITIAL
#router.register(r"^map/{idf}/$", MarkerViewSet) #I tried this
#router.register(r"^map/(?P<idf>[0-9]+)/$", MarkerViewSet) #this generate an error because of idf 
router.register(r"^map/(?P<id_f>[0-9]+)/$", MarkerViewSet)
urlpatterns = router.urls

Another error message is on Firefox: enter image description here

I believe, I should find the right format, but something else should be wrong

Many thanks for your help

pierrot10
  • 1
  • 3