Multiple filtering Django Rest Framework

4

I wanted to do a multiple filtering by url with the API Django Rest Framework that is to say that for example type www.domain.com/clientes/Nike/ES and return me all Nike customers from Spain, the thing is that I do not know how to cross the tables, right now I have managed to filter by id www.domain.com/clientes/1 / the thing is that Nike is not the id of your table and ES is not the id of your table, and I do not know how to filter by different fields other than the id and cross tables to return the JSON with the fields that I am interested in, it does not I miss the whole brand but you give me your name or the desired field in particular.

api / views.py

class ClienteViewset(ModelViewSet):
      serializer_class = ClienteSerializer
      queryset = ClienteModel.object.all()
      lookup_field = 'cliente_id'

cliente_list = ClienteViewset.as_view({'get': 'list'})
cliente_detail = ClienteViewset.as_view({'get': 'retrieve'})

api / urls.py

router.register(r'clientes', ClienteViewset)

urlpatterns = patterns('api.views',
    url(r'^', include(router.urls))
)

serializers.py

class ClienteSerializer(ModelSerializer):
     class Meta:
         model = Cliente
         fields = ('cliente_id', 'cliente_nombre', 'cliente_apellidos')

If anyone knows how I can do it, it would be very helpful, even with the objects nested inside the JSON.

The thing is that I have a quite complex database in terms of relations, since I have texts by languages, brands, etc ...

    
asked by RuralGalaxy 19.05.2016 в 11:02
source

1 answer

3

Why do not you use the generic filters provided by DRF through DjangoFilterBackend?

Here on the documentation mention it. You just have to install django-filter and class DjangoFilterBackend as a filter backend, it would be something like this:

from django_filters.rest_framework import DjangoFilterBackend

class ClienteViewset(ModelViewSet):
      serializer_class = ClienteSerializer
      queryset = ClienteModel.object.all()
      filter_backends = (DjangoFilterBackend,)
      filter_fields = ('cliente_nombre', 'paises__codigo')

and then the filter would be like this: www.domain.com/clientes/?cliente_nombre=Nike&paises__codigo=ES

On the other hand, if you really want to filter values in the urls /{param1}/{param2}/ instead of parameters ?param1=val1&param2=val2 you can install nested -routes that makes it easier for you to do that.

    
answered by 04.04.2017 в 17:46