Evgenii Legotckoi
Feb. 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

  1. 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.

  1. <form method="get">
  2. <button type="submit" class="btn btn-sm btn-primary btn-raised mr-3">{% trans 'Сортировать' %}</button>
  3. <input name="sort" type="checkbox" value="title" {{ by_title }}>{% trans "по заголовку" %}
  4. <input name="sort" type="checkbox" value="pub_date" {{ by_date }}>{% trans "по дате" %}
  5. <input name="sort" type="checkbox" value="views" {{ by_views }}>{% trans "по просмотрам" %}
  6. </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:

  1. ?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

  1. class SectionView(View):
  2.  
  3. def get(self, request, slug):
  4. section = get_object_or_404(Section, slug=slug)
  5. sort = request.GET.getlist('sort')
  6. articles = section.article_set.all().order_by(*sort)
  7.  
  8. return render(
  9. request=request,
  10. template_name='knowledge/section.html',
  11. context={
  12. 'section': section,
  13. 'articles': articles
  14. }
  15. )

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.

  1. sort = request.GET.getlist('sort')

And then with the help of the pointer we pass the list as arguments to the order_by method

  1. articles = section.article_set.all().order_by(*sort)

For Django I recommend VDS-server of Timeweb hoster .

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
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html