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
ОН

C++ - Test 006. Enumerations

  • Result:10points,
  • Rating points-10
K
  • KiRi4
  • Sept. 7, 2023, 2:57 p.m.

C++ - Test 002. Constants

  • Result:41points,
  • Rating points-8
K
  • KiRi4
  • Sept. 7, 2023, 2:49 p.m.

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

  • Result:66points,
  • Rating points-1
Last comments
IscanderChe
IscanderCheSept. 13, 2023, 4:11 p.m.
QScintilla C++ example По горячим следам (с другого форума вопрос задали, пришлось в памяти освежить всё) решил дополнить. Качаем исходники с https://riverbankcomputing.com/software/qscintilla/downlo…
Evgenii Legotckoi
Evgenii LegotckoiSept. 6, 2023, 2:18 p.m.
Qt/C++ - Lesson 048. QThread — How to work with threads using moveToThread Разве могут взаимодействовать объекты из разных нитей как-то, кроме как через сигнал-слоты?" Могут. Выполняя оператор new , Вы выделяете под объект память в куче (heap), …
AC
Andrei CherniaevSept. 5, 2023, 10:37 a.m.
Qt/C++ - Lesson 048. QThread — How to work with threads using moveToThread Я поясню свой вопрос. Выше я писал "Почему же в методе MainWindow::on_write_1_clicked() Можно обращаться к методам exampleObject_1? Разве могут взаимодействовать объекты из разных…
n
nvnAug. 31, 2023, 4:47 p.m.
QML - Lesson 004. Signals and Slots in Qt QML Здравствуйте! Прекрасный сайт, отличные статьи. Не хватает только готовых проектов для скачивания. Многих комментариев типа appCore != AppCore просто бы не было )))
NSProject
NSProjectAug. 24, 2023, 8:40 p.m.
Django - Tutorial 023. Like Dislike system using GenericForeignKey Ваша ошибка связана с gettext from django.utils.translation import gettext_lazy as _ Поле должно выглядеть так vote = models.SmallIntegerField(verbose_name=_("Голос"), choices=VOTES) …
Now discuss on the forum
IscanderChe
IscanderCheSept. 17, 2023, 4:24 p.m.
Интернационализация строк в QMessageBox Странная картина... Сделал минимально работающий пример - всё работает. Попробую на другой операционке. Может, дело в этом.
NSProject
NSProjectSept. 17, 2023, 3:49 p.m.
Помогите добавить Ajax в проект В принципе ничего сложного с отправкой на сервер нет. Всё что ты хочешь отобразить на странице передаётся в шаблон и рендерится. Ты просто создаёшь файл forms.py в нём описываешь свою форму и в …
BlinCT
BlinCTSept. 15, 2023, 7:35 p.m.
Размеры полей в TreeView Всем привет. Пытаюсь сделать дерево вот такого вида Пытаюсь организовать делегат для каждой строки в дереве. ТО есть отступ какого то размера и если при открытии есть под…
IscanderChe
IscanderCheSept. 8, 2023, 7:07 p.m.
Кастомная QAbstractListModel и цвет фона, цвет текста и шрифт Похоже надо не абстрактный , а "реальный" типа QSqlTableModel Да, но не совсем. Решилось с помощью стайлшитов и setFont. Спасибо за отлик!
Evgenii Legotckoi
Evgenii LegotckoiSept. 6, 2023, 1:35 p.m.
Вопрос: Нужно ли в деструкторе удалять динамически созданные QT-объекты. Напр: Зависит от того, как эти объекты были созданы. Если вы передаёте указатель на parent объект, то не нужно, Ядро Qt само разрулит удаление, если нет, то нужно удалять вручную, иначе будет ут…

Follow us in social networks