33👍
✅
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
7👍
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
- poster = 1
- tasker = 115
- status = O
-
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:
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
- [Django]-What is the equivalent of django.db.models.loading.get_model() in Django 1.9?
- [Django]-Django, Turbo Gears, Web2Py, which is better for what?
- [Django]-Django Filter Query Foreign Key
2👍
For me, it works when I put the comma at the end of my filter_fields.
eg.
filter_fields = ('distribuidor',)
- [Django]-Error trying to install Postgres for python (psycopg2)
- [Django]-Django: csrftoken COOKIE vs. csrfmiddlewaretoken HTML Form value
- [Django]-Consolidating multiple post_save signals with one receiver
Source:stackexchange.com