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?
mariodev :
You need to define filter backend and all related fields you're planning to filter on:\n\nclass EstablecimientoViewSet(viewsets.ModelViewSet):\n filter_backends = (filters.DjangoFilterBackend,)\n filter_fields = ('categoria', 'categoria__titulo',)\n\n\nexample:\n\nURL?categoria__titulo=Categoria 1\n",
2014-01-27T08:56:02
DmitrySemenov :
it's also possible to supply your own Filter class, which may give you more options and flexibility\n\nimport sys, django_filters, json, io\n\nclass TaskFilter(django_filters.FilterSet):\n tag = django_filters.CharFilter(name='tags__name', lookup_type='iexact')\n university = django_filters.NumberFilter(name='poster__university', lookup_type='exact')\n\n class Meta:\n model = Task\n fields = {\n 'poster': ['exact'],\n 'tasker': ['exact'],\n 'status': ['exact'],\n 'created': ['lt', 'gt']\n }\n\n\nIn this example I got filters\n\n\nposter = 1 \ntasker = 115 \nstatus = O \ncreated__lt=2015-09-22\n17:39:01.184681 (so I can filter datetime by values LESS THEN)\ncreated__gt=2015-09-22 17:39:01.184681 (or GREATER THAN provided\nvalue)\n\n\nAlso I can hide foreign fields with custom filter fields, in this case it's tag & university. Plus I can provide comparison operator (lookup_type)\n\nSample request:\n\nGET /api/v1/tasks/?offset=0&status=O&limit=100&university=1&ordering=-created&created__lt=2015-09-22 17:39:01.184681&tag=sport HTTP/1.1\nHost: domain.com\nContent-Type: application/json\nAuthorization: token 61cbd3c7c2656d4e24edb31f5923a86910c67b7c\nUser-Timezone: US/Pacific\nCache-Control: no-cache\n",
2015-09-29T01:39:20