未显示搜索结果

问题描述 投票:0回答:1

我创建了一个名为Product的模型,其中包含以下字段(“ prod_name”,“ company”,“ quantity”,“ price”,“ units”,“ prod_type”),因此,每当我使用搜索栏搜索名称时公司不展示产品的信息

这是我的views.py文件(仅包含搜索视图)

from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import TemplateView, ListView
from django.db.models import Q
from .models import *
from .forms import *

class SearchResultsView(ListView):
      model = Product
      template_name = 'search_results.html'

      def get_queryset(self):
          query = self.request.GET.get('q')
          items=Product.objects.filter(Q(company__icontains=query))

          return items

包含搜索栏的base.html文件

<form class="form-inline my-2 my-md-0" action="{% url 'search_results' %}" method="get">
     <input class="form-control" name="q" type="text" placeholder="Search">
</form>

search_results.html文件

{% extends 'base.html' %}

{% block body %}

<br>

<br>

<table class="table table-hover">
    <thead>
        <tr>
            <th>Sr. No.</th>
            <th>Product Name</th>
            <th>Company</th>
            <th>Quantity</th>
            <th>Price</th>
            <th>Units</th>
            <th>Product Type</th>
        </tr>
    </thead>
    <tbody>

        {% for item in items %}

        <tr>
            <td>{{item.pk}}</td>
            <td>{{item.prod_name}}</td>
            <td>{{item.company}}</td>
            <td>{{item.quantity}}</td>
            <td>{{item.price}}</td>
            <td>{{item.units}}</td>
            <td>{{item.prod_type}}</td>
        </tr>


    {% endfor %}

</tbody>
</table>    

{% endblock %}

urls.py文件

from django.conf.urls import url
from django.urls import path
from .views import *
urlpatterns=[
    path('search/', SearchResultsView.as_view(), name='search_results'),
]

这是我搜索某物后的外观enter image description here

python html django search
1个回答
1
投票
    # you just have to remove "Q" from your query

    from django.shortcuts import render, redirect, get_object_or_404
    from django.views.generic import TemplateView, ListView
    from .models import *
    from .forms import *

    class SearchResultsView(ListView):
          model = Product
          template_name = 'search_results.html'

          def get_queryset(self):
              query = self.request.GET.get('q')
              items=Product.objects.filter(company__icontains=query)

              return items


# In your template, you have a change


{% for item in object_list %}

        <tr>
            <td>{{item.pk}}</td>
            <td>{{item.prod_name}}</td>
            <td>{{item.company}}</td>
            <td>{{item.quantity}}</td>
            <td>{{item.price}}</td>
            <td>{{item.units}}</td>
            <td>{{item.prod_type}}</td>
        </tr>


    {% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.