Есть ли способ выполнить фильтрацию списка в django generic ListView, как в админке django?

Я пытаюсь добавить фильтрацию для представления списка в django, что-то вроде enter image description here

Вот мое мнение

class SaleView(ListView):
    model = SaleBill
    template_name = "sales/sales_list.html"
    context_object_name = "bills"
    ordering = ["-time"]
    paginate_by = 10

и мой шаблон

Я просмотрел код Django

и я не уверен, что это единственный способ добавить эту функциональность или есть более простой способ.

Проще способ? ДА. Вам просто нужно переопределить метод get_queryset представления списка.

class SaleView(ListView):
    model = SaleBill
    template_name = "sales/sales_list.html"
    context_object_name = "bills"
    ordering = ["-time"]
    paginate_by = 10
    
    def get_queryset(self):
    # Here we try to filter by status
    status = self.kwargs.get('ststus', None)
    # If a the key 'status' is set in the url
    if status:
        if status == 'new':
            return super(SaleView, self).get_queryset().filter(
                status='new')
        elif status == 'open':
            return super(SaleView, self).get_queryset().filter(
                status='open')
        else:  # the last status is 'canceled'
            return super(SaleView, self).get_queryset().filter(
                status='canceled')
    else:  # The key status is not set in the url
        # Return the default queryset without filter
        return super(SaleView, self).get_queryset()

template.html. Вот как вы можете отобразить эти различные ссылки

<ul class='filter'>
    <!-- This one is the default (no filter) -->
    <li><a href="{% url 'list_view' status='' %}">All</a></li>
    <!-- Others filter option (no filter) -->
    <li><a href="{% url 'list_view' status='new' %}">New</a></li>
    <li><a href="{% url 'list_view' status='open' %}">Open</a></li>
    <li><a href="{% url 'list_view' status='canceled' %}">Canceled</a></li>
</ul>

Измените его в соответствии с вашими потребностями.

Вернуться на верх