To improve the usability of article sections, we sorted articles by date, title, and number of views. In addition, the ability to find information on articles of the section has been added. This feature is implemented through several checkboxes that add the column names for sorting in the URL of the page, respectively, the page is reloaded.
For example, there are several columns in the data model
- title
- pub_date
- views
For them we will do the sorting, which in the usual query would look like this
Article.objects.all().order_by('title', 'pub_date', 'views')
But since we use checkboxes, sorting options can be present, and I can be absent. But do not we write if else blocks for every combination of checkboxes? Of course not.
Let's see to the beginning how a form can be written to implement sorting. At once I will make a reservation, that I will result a variant of the form without stylization, which is applied on my site. The fact is that Bootstrap 4 Material Design is used for this, which somewhat complicates the layout option and adds a number of extra elements to the example.
<form method="get"> <button type="submit" class="btn btn-sm btn-primary btn-raised mr-3">{% trans 'Сортировать' %}</button> <input name="sort" type="checkbox" value="title" {{ by_title }}>{% trans "по заголовку" %} <input name="sort" type="checkbox" value="pub_date" {{ by_date }}>{% trans "по дате" %} <input name="sort" type="checkbox" value="views" {{ by_views }}>{% trans "по просмотрам" %} </form>
As you can see, all the checkboxes in the code have the name sort, and the value value will be equal to the column name, by which you can enable sorting.
Thus, the following arguments will appear in the URL:
?sort=title&sort=pub_date&sort=views
Django allows you to extract all the arguments from the query as a list, which we can pass to the order_by method to perform the sorting.
And actually the rendering for the section with articles might look like this
class SectionView(View): def get(self, request, slug): section = get_object_or_404(Section, slug=slug) sort = request.GET.getlist('sort') articles = section.article_set.all().order_by(*sort) return render( request=request, template_name='knowledge/section.html', context={ 'section': section, 'articles': articles } )
Note that instead of the get method, the getlist method is used, which returns a list of argument values if the query has the same argument name several times.
sort = request.GET.getlist('sort')
And then with the help of the pointer we pass the list as arguments to the order_by method
articles = section.article_set.all().order_by(*sort)
For Django I recommend VDS-server of Timeweb hoster .
Ну. Массово пока не использую фильтрации, поэтому не искал батареек. Так получилось, что даже не знал про django-filters.
хорошие статьи я много чего нашел тут интересного и нового... мне нравиться!
если вдруг интересно будет по фильтрам вот примерный код)
Спасибо за пример кода.
Когда буду внедрять больше поисковых виджетов на сайт, в первую очередь воспользуюсь вашим примером кода. Благо уже есть некоторые целевые места, где это можно применить.