我创建了一个名为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'),
]
答案 0 :(得分: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 %}