Django模型搜索不会返回任何值

时间:2019-05-30 06:06:05

标签: django

我正在尝试创建一个搜索函数,该函数将基于idasset_name返回表中的相应值,但是当我搜索有效的{{1}时它不返回任何内容}或id。我的代码中缺少什么吗?

Views.py

asset_name

Urls.py

def search(request):
template = 'blog/home.html'  

query = request.GET.get('q') 

if query:
    results = Post.objects.filter(Q(id__icontains=query) | Q(asset_name__icontains=query))
else:
    results = Post.objects.filter(status="Published")

context = {
    'query': query
}
return render(request, template, context)

class PostListView(ListView):
model = Post
template_name = 'blog/home.html' 
context_object_name = 'posts'
ordering = ['-date_posted']

Home.html

urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('results/', search, name='search'),
]

1 个答案:

答案 0 :(得分:0)

在您的模板中,您没有在posts视图中发送search作为上下文。这就是为什么迭代% for post in posts %}无法正常工作的原因。我认为使用这种方式更简单:

模板

<form method="GET" action="{% url 'results' %}">
 <input type="text" name="q" value="{{query}}" placeholder="Search for project" />
 <input type="submit" value="Search" />
</form>

<tbody>
{% for post in posts %}
<tr data-href="linkToFile.pdf"> 
<td>{{ post.id }}{% if query %}&q={{query}}{% endif %}</td>
<td><a href="{% url 'post-detail' post.id %}">{{ post.asset_name }}{% if query %}&q={{query}}{% endif %}</a></td>
</tr>
{% endfor %}
</tbody>

查看

class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html' 
    context_object_name = 'posts'
    ordering = ['-date_posted']

    def get_context_data(self, **kwargs):
        context = super(PostListView, self).get_context_data(**kwargs)
        query = request.GET.get('q') 
        if query:
           context['posts'] = Post.objects.filter(Q(id__icontains=query) | Q(asset_name__icontains=query))
           context['query'] = query
        return context

通过这种方式,您可以使用一个PostListView视图来获得搜索和列表视图,也不需要使用额外的视图来显示搜索结果。