如何使用“ Django过滤器”从不同类别进行搜索?

时间:2019-03-25 13:56:37

标签: django django-filter

我用过django_filters,下面是代码:

from .models import Product
import django_filters

class ProductFilter(django_filters.FilterSet):
    product_name = django_filters.CharFilter(lookup_expr='icontains', label='Product Name')
    product_price = django_filters.NumberFilter()
    product_price__gt = django_filters.NumberFilter(field_name='product_price', lookup_expr='gt', label='Min Price')
    product_price__lt = django_filters.NumberFilter(field_name='product_price', lookup_expr='lt', label='Max price')
    hotel_location = django_filters.CharFilter(lookup_expr='icontains', label='hotel location')
    product_category = django_filters.CharFilter(lookup_expr='icontains', label='product category')


    class Meta:
        model = Product
        fields = ['product_name', 'product_price', 'vendor_name', 'hotel_location', 'product_category']

视图功能包含以下代码,用于在模板中显示

def searchTable(request):
    product_list = Product.objects.all()
    product_filter = ProductFilter(request.GET, queryset=product_list)
    return render(request, 'searchTable.html', {'filter': product_filter})

与此相关的html代码是:

<form method="get">
  .......
 </form>

<table class="table table-hover table-striped table-bordered table-dark" id="myTable">
        <thead style="background-color: #3e4e6f; color: white">
        <tr>
            <th>Image</th>
            <th>Product Name</th>
            <th>Price</th>
            <th>Vendor</th>
        </tr>
        </thead>
        <tbody >

        {% for lap in filter.qs|slice:":100" %}

            <tr>
                <td class="col-sm-3">
                    <div>
                        <div class="product-image-wrapper">
                            <div class="single-products">
                                <div class="productinfo text-center">
                                    <img src="{{ lap.product_image }}" alt=""/>
                                </div>
                            </div>
                        </div>
                    </div>
                </td>
                <td class="col-sm-5">

                    <h5><a href="{{ lap.product_url }}">{{ lap.product_name }}</a></h5>
                    <br>

                    <a href="{{ lap.product_url }}" class="btn btn-secondary" role="button" aria-pressed="true"

                       style="background-color: #3e4e6f; color: white">See Details</a>

                </td>

                <td class="col-sm-2">{{ lap.product_price }} &#2547;</td>
                <td class="col-sm-2">{{ lap.vendor_name }}</td>

            </tr>

        {% empty %}
            <tr>
                <td colspan="5">No Result Found</td>
            </tr>

        {% endfor %}



        </tbody>
    </table>

现在我的问题是,product_category中有不同的类别。如何显示任何特定类别的产品?例如,product_category="laptop"

0 个答案:

没有答案