get () returned more than one Location - it returned 2!

1

I have routes associated with locations, I want that when I type ' link ' I return all the locations with the path of id 11 but if you have two or more I get the error: "MultipleObjectsReturned at / rest / Location / 11 /

get () returned more than one Location - it returned 2! "

My models is as follows:

class Ubicacion(models.Model):
 nombre = models.CharField(max_length=200)
 lat  = models.CharField(max_length=50)
 lng = models.CharField(max_length=50)
 fecha = models.DateTimeField(auto_now_add=True)
 docfile = models.FileField(upload_to='')
 user = models.ForeignKey(User,on_delete=models.PROTECT)
 descripcion = models.CharField(max_length=500)
 TextoParaAudio = models.CharField(max_length=100)
 Ruta = models.ForeignKey(Ruta,on_delete=models.PROTECT)

My viewsets:

class UbicacionViewSetById(viewsets.ModelViewSet):

 serializer_class = UbicacionSerializer

 def get_queryset(self):
     id = self.kwargs['id']

     return Ubicacion.objects.filter(Ruta=id).order_by('id')

my urls:

router.register(r'UbicacionById',UbicacionViewSetById.get_queryset,base_name="UbicacionById")     

urlpatterns=[
    url(r'^admin/Rutas/ubicacion/add/', include("Rutas.urls")),
    url(r'^admin/', admin.site.urls),
    url(r'^rest/', include(router.urls)),


] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Thank you very much!

    
asked by Marta 10.04.2018 в 10:26
source

2 answers

0

What you want to do is filter a list, for this you have to pass parameters with the GET method:

link

and modify the get_queryset method of the Location_ViewSetById class

 def get_queryset(self):
     id = self.request.GET.get('ruta')

     return Ubicacion.objects.filter(Ruta__pk=id).order_by('id')

#te recomendaria que cambies el UbicacionById por ubicaciones, siempre en plural en minúsculas, observa que he quitada el .get_queryset
router.register(r'UbicacionById',UbicacionViewSetById,base_name="UbicacionById")     

when you just put the viewset on the router, and you call link this automatically calls the get_queryset if you want to filter add the parameters with GET? route = 11

link with this will automatically return the location with id = 12

routers good practices APIRest

    
answered by 11.04.2018 / 23:09
source
0

You are using the detail method and you are returning multiple objects. When you pass the id at the end you are saying "give me the location with id 11" and then in the viewset you are modifying the queryset and sending several. The simplest way is to create a function with the decorator @list_route() and pass it as parameter the route id, make the filter as you are doing in get_queryset() and then you do this:

serializer = self.get_serializer(queryset,many=True)
return Response(serializer.data)

self.get_serializer can be translated by serializer UbicacionSerializer if the function is taken from viewset

    
answered by 10.04.2018 в 10:37