Evgenii Legotckoi
Evgenii LegotckoiFeb. 28, 2018, 4:57 a.m.

Django - Tutorial 033. Passing the argument list to the order_by method to sort the QuerySet

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 .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

bernar92
  • May 16, 2018, 11:53 p.m.
можно же это реализовать через django-filter!
Evgenii Legotckoi
  • May 17, 2018, 2:05 a.m.

Ну. Массово пока не использую фильтрации, поэтому не искал батареек. Так получилось, что даже не знал про django-filters.

Спасибо. Можете черкануть заметку, как аналог этой статье ;-)
bernar92
  • May 17, 2018, 11:16 a.m.

хорошие статьи я много чего нашел тут интересного и нового... мне нравиться!
если вдруг интересно будет по фильтрам вот примерный код)

import django_filters
from .models import Product

CHOICES =[
        ["name", "по алфавиту"],
        ["price", "дешевые сверху"],
        ["-price", "дорогие сверху"]
]


class ProductFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(name='name', lookup_expr='icontains')
    category__slug = django_filters.CharFilter()
    price__gt = django_filters.NumberFilter(name='price', lookup_expr='gt')
    price__lt = django_filters.NumberFilter(name='price', lookup_expr='lt')
    ordering = django_filters.OrderingFilter(choices=CHOICES, required=True, empty_label=None,)

    class Meta:
        model = Product
        exclude = [field.name for field in Product._meta.fields]
        order_by_field = 'name'


from django_filters.views import FilterView
class EnumerationListView(FilterView):
    template_name = '.html'
    model = Lot
    paginate_by = 50
    filterset_class = ProductFilter
    context_object_name = 'product_list'

Evgenii Legotckoi
  • May 17, 2018, 4:23 p.m.

Спасибо за пример кода.
Когда буду внедрять больше поисковых виджетов на сайт, в первую очередь воспользуюсь вашим примером кода. Благо уже есть некоторые целевые места, где это можно применить.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 9:29 p.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 1:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 9:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 11:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 7:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks