pip install django-filter
INSTALLED_APPS = [
~
'django_filters',
]
views.py
def TutorialsList(request):
tutorials = TutorialList.objects.all()
myFilter = TutorialFilter(request.GET, queryset=tutorials)
tutorials = myFilter.qs
return render(request, 'tutorial_list.html',
{'tutorials': tutorials, 'myFilter':myFilter})
create a new file filters.py
filters.py
gt means greater than (gte: equal to)
import django_filters
from django_filters import DateFilter
from .models import *
class TutorialFilter(django_filters.FilterSet):
date = DateFilter(
field_name='last_updated', lookup_expr='gt')
class Meta:
#minimum of two attr
model = TutorialList
#1) specific fields
fields = ('title', 'instructor', 'language')
#2) all & exclude(override all)
fields = '__all__'
exclude = ['last_updated', 'description' ]
template
<form method="get">
{{ myFilter.form }}
</form>
Example:
URL: when filter with instructor and difficulty
http://127.0.0.1:8000/tutorial_list/
?title=
&instructor=Dennis+Ivy
&language=
&difficulty=Intermediate
&last_updated=
https://www.youtube.com/watch?v=nle3u6Ww6Xk
search available only with certain text within sentence
fields = {
'title': ['icontains'],
'instructor': ['icontains'],
}
class TutorialFilter(django_filters.FilterSet):
DATE_CHOICES = (
('newest', 'Newest'),
('oldest', 'Oldest')
)
date_sort = django_filters.ChoiceFilter(
label='Sort by Date ',
choices=DATE_CHOICES, method='filter_by_date')
class Meta:
~
def filter_by_date(self, queryset, name, value):
expression = 'last_updated'
if value == 'oldest' else '-last_updated'
return queryset.order_by(expression)
https://simpleisbetterthancomplex.com/tutorial
/2016/11/28/how-to-filter-querysets-dynamically.html
exact: when it's choices, it will show dropdown
year__gt: greater than
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
fields = {
'username': ['exact', ],
'first_name': ['icontains', ],
'last_name': ['exact', ],
'date_joined': ['year', 'year__gt', 'year__lt', ],
https://stackoverflow.com/questions/49732359/check-and-clear-filters-with-django-filter
https://stackoverflow.com/questions/36871987/django-filter-change-default-form-appearance