Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework filter

Tags:

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?

like image 916
user3236034 Avatar asked Jan 27 '14 06:01

user3236034


People also ask

What is the use of Django filter?

Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this.

What is Queryset in Django REST framework?

The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.


2 Answers

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 
like image 87
mariodev Avatar answered Oct 01 '22 19:10

mariodev


it's also possible to supply your own Filter class, which may give you more options and flexibility

import sys, django_filters, json, io  class TaskFilter(django_filters.FilterSet):     tag  = django_filters.CharFilter(name='tags__name', lookup_type='iexact')     university = django_filters.NumberFilter(name='poster__university', lookup_type='exact')      class Meta:         model = Task         fields = {             'poster': ['exact'],             'tasker': ['exact'],             'status': ['exact'],             'created': ['lt', 'gt']         } 

In this example I got filters

  1. poster = 1
  2. tasker = 115
  3. status = O
  4. created__lt=2015-09-22 17:39:01.184681 (so I can filter datetime by values LESS THEN)

  5. 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:

GET /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 Host: domain.com Content-Type: application/json Authorization: token 61cbd3c7c2656d4e24edb31f5923a86910c67b7c User-Timezone: US/Pacific Cache-Control: no-cache 
like image 29
DmitrySemenov Avatar answered Oct 01 '22 19:10

DmitrySemenov