Customizing Views (2) – Filter Lists
Using the queryset
attribute and the filter
method, you can filter the list shown on the list page. Here we'll explain how to use them with the employee learning app example.
Filter objects with the field that matches a keyword
To display only basic-level courses, edit the CourseList view by adding the yellow part of the code below. Also, comment out the previous one.
class CourseList(ListView):
# model = LearningCourse
# queryset = LearningCourse.objects.order_by('-title')
queryset = LearningCourse.objects.filter(level='B')
:
You can see that only basic courses are shown.
Customize filtering
The filter method also has the functionality to customize filtering approaches.
Here are some examples:
filter(field__contains='keyword')
: Filter objects that contain 'keyword'filter(field__startwith='keyword')
: Filter objects that start with 'keyword'filter(field__endwith='keyword')
: Filter objects that end with 'keyword'filter(field__gt='number or string')
: Filter objects that are greater than 'number or string'filter(field__gte='number or string')
: Filter objects that are greater than or equal to 'number or string'filter(field__lt='number or string')
: Filter objects that are lower than 'number or string'filter(field__lte='number or string')
: Filter objects that are lower than or equal to 'number or string'
For example, if you want to get the courses whose names include 'Docker', use filter(title__contains='Docker')
. To implement this, edit the CourseList view by replacing the yellow part of the code below.
class CourseList(ListView):
# model = LearningCourse
# queryset = LearningCourse.objects.order_by('-title')
queryset = LearningCourse.objects.filter(title__contains='Docker')
:
You can see that only Docker courses are shown.