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
OI

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

  • Result:40points,
  • Rating points-8
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 7:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 9:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 3:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 2:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 6:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Donald Randolph
Donald RandolphDec. 30, 2024, 10:59 a.m.
Personal Injury lawyer Santa Monica As an experienced Santa Monica personal injury lawyer, Donald C. Randolph has recovered over $100 Million in verdicts and settlements for our clients. In severe injury cases, this compensation i…
Nirvana Yoga School
Nirvana Yoga SchoolDec. 30, 2024, 1:13 p.m.
OAuth2.0 через VK, получение email Nirvana Yoga School is one of the most trusted and reputed traditional Rishikesh yoga courses , India certified by Yoga Alliance, USA. We aim to spread traditional yoga teachings so t…
s
sriparkDec. 30, 2024, 12:47 p.m.
Mobile app development company in Chennai A Mobile app development company in Chennai focuses on creating personalized mobile applications to meet various business requirements. These companies offer a full range of services,…
a
amit88Dec. 30, 2024, 12:45 p.m.
Excel in Exams with PSLE Maths Tuition Singapore Preparing for the PSLE can be challenging, but the right guidance makes all the difference. PSLE Maths tuition Singapore offers personalized coaching to help students master key concepts, improv…
a
awinash62Dec. 30, 2024, 12:23 p.m.
Unlock Your Potential with the Certified Public Accountant Credential" Becoming a Certified Public Accountant (CPA) is a career milestone that opens doors to unparalleled opportunities in the world of accounting and finance. This globally recognized qualification s…

Follow us in social networks