django rest framework filter

user3236034 picture user3236034 · Jan 27, 2014 · Viewed 28.9k times · Source

I'm working with API made from Django rest framework, I am trying to make a filter to a JSON This is my serializers.py file

from rest_framework import serializers
from .models import Establecimiento,Categoria,Ciudad,Zona
import django_filters

class EstablecimientoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Establecimiento
        depth = 1

        fields =  ('nombre',
                   'ciudad',
                   'categoria',
                   'direccion',
                   'telefono',
                   'precioMinimo',
                   'precioMaximo',)

and this my views.py file

from rest_framework import viewsets
from .serializers import EstablecimientoSerializer, CategoriaSerializer
from models import *
from rest_framework import filters
from rest_framework import generics

class EstablecimientoViewSet(viewsets.ModelViewSet):
    queryset = Establecimiento.objects.all()
    serializer_class = EstablecimientoSerializer
    filter_fields = ('categoria',)

Then in the EstablecimientoViewSet class, I put a filter_fields = ('categoria',) to filter the url's API with the category field

If I add the filter to the query parameters, the result set does not change, it shows all data unfiltered.

...establecimiento?establecimiento=bar

How can I make this filter about this model?

Answer

mariodev picture mariodev · Jan 27, 2014

You need to define filter backend and all related fields you're planning to filter on:

class EstablecimientoViewSet(viewsets.ModelViewSet):
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('categoria', 'categoria__titulo',)

example:

URL?categoria__titulo=Categoria 1