Evgenii Legotckoi
Evgenii LegotckoiFeb. 28, 2018, 3:57 p.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 17, 2018, 9:53 a.m.
можно же это реализовать через django-filter!
Evgenii Legotckoi
  • May 17, 2018, 12:05 p.m.

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

Спасибо. Можете черкануть заметку, как аналог этой статье ;-)
bernar92
  • May 17, 2018, 9:16 p.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 18, 2018, 2:23 a.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
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
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 8, 2024, 3:43 p.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, 7:30 a.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, 5:38 a.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. 18, 2023, 6:01 p.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
AC
Alexandru CodreanuJan. 19, 2024, 8:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 5:57 a.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 1:18 a.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 3:48 a.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks