【问题标题】:Sort by ascending and descending using django-filter使用 django-filter 按升序和降序排序
【发布时间】:2019-01-26 21:56:41
【问题描述】:

我有以下几个过滤代码:

from .models import ProductLaptop
import django_filters

class ProductLaptopFilter(django_filters.FilterSet):
    laptops_name = django_filters.CharFilter(lookup_expr='icontains')
    laptops_price = django_filters.NumberFilter()
    laptops_price__gt = django_filters.NumberFilter(field_name='laptops_price', lookup_expr='gt')
    laptops_price__lt = django_filters.NumberFilter(field_name='laptops_price', lookup_expr='lt')


    class Meta:
        model = ProductLaptop
        fields = ['laptops_name', 'laptops_price', 'brand_name']

这个的html代码:

{% load widget_tweaks %}

{% block content %}
  <form method="get">
    <div class="well">
      <h4 style="margin-top: 0">Filter</h4>
      <div class="row">
        <div class="form-group col-sm-4 col-md-3">
          {{ filter.form.laptops_name.label_tag }}
          {% render_field filter.form.laptops_name class="form-control" %}
        </div>
        <div class="form-group col-sm-4 col-md-3">
          {{ filter.form.laptops_price.label_tag }}
          {% render_field filter.form.laptops_price class="form-control" %}
        </div>
        <div class="form-group col-sm-4 col-md-3">
          {{ filter.form.brand_name.label_tag }}
          {% render_field filter.form.brand_name class="form-control" %}
        </div>
        <div class="form-group col-sm-4 col-md-3">
          {{ filter.form.laptops_price__gt.label_tag }}
          {% render_field filter.form.laptops_price__gt class="form-control" %}
        </div>
      <div class="form-group col-sm-4 col-md-3">
          {{ filter.form.laptops_price__lt.label_tag }}
          {% render_field filter.form.laptops_price__lt class="form-control" %}
        </div>

      </div>
      <button type="submit" class="btn btn-primary">
        <span class="glyphicon glyphicon-search"></span> Search
      </button>
    </div>
  </form>

这给了我如下视图:

在这里我想添加一个选项,人们可以按升序和降序对项目进行排序。 谁能给我一些建议,我该如何实施?

【问题讨论】:

    标签: django django-filter


    【解决方案1】:

    为此,您可以使用django-filter 中的OrderingFilter。在您的 FilterSet 类中创建此过滤器,并提供应启用排序的所有字段。

    【讨论】:

      猜你喜欢
      • 2012-11-08
      • 2023-03-07
      • 2017-11-16
      • 1970-01-01
      • 2011-08-25
      • 2021-01-23
      • 2018-11-20
      • 1970-01-01
      • 2012-12-21
      相关资源
      最近更新 更多