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?
You need to define filter backend and all related fields you're planning to filter on:
example:
For me, it works when I put the comma at the end of my filter_fields.
eg.
it's also possible to supply your own Filter class, which may give you more options and flexibility
In this example I got filters
created__lt=2015-09-22 17:39:01.184681 (so I can filter datetime by values LESS THEN)
created__gt=2015-09-22 17:39:01.184681 (or GREATER THAN provided value)
Also I can hide foreign fields with custom filter fields, in this case it's tag & university. Plus I can provide comparison operator (lookup_type)
Sample request: