如何解决Django Postgresql 搜索不显示结果
我正在制作一个 Django 网站,该网站具有使用 Postgres 的全文搜索。但是,当我进行搜索时,没有任何结果出现。我做错了什么吗?这是我的代码:
视图.py
from django.shortcuts import render
from django.contrib.postgres.search import SearchVector,SearchQuery,SearchRank
from django.views.generic import ListView,FormView
from .models import Post
from .forms import *
# Create your views here.
class HomepageView(FormView):
template_name = 'selling/home.html'
form_class = SearchForm
class Search(ListView):
model = Post
template_name = 'selling/search.html'
def get_queryset(self):
query = self.request.GET.get('q')
posts = Post.objects.annotate(
search=SearchVector('title','description'),).filter(search=SearchQuery(query))
return posts
模型.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.Now)
author = models.ForeignKey(User,on_delete=models.CASCADE)
book_author = models.CharField(max_length=30)
phone_contact = models.CharField(max_length=20)
price = models.DecimalField(max_digits=7,decimal_places=2)
postal_code = models.CharField(max_length=20)
def __str__(self):
return self.title
Forms.py
from django import forms
class SearchForm(forms.Form):
q = forms.CharField(label='Search',max_length=50)
搜索.html
{% extends "selling/base.html" %}
{% load static %}
{% block content %}
<div class="container pt-5 pb-5">
<div class="ui divided items">
{% for item in posts %}
<div class="item">
<div class="image">
<img src="{% static 'selling/images/brebeuf.png' %}">
</div>
<div class="content item-container">
<a class="header item-title">{{ item.title }} </a><b class="item-price-right">${{ item.price }}</b>
<div class="Meta">
<span>{{ item.postal_code }}   |   {{ item.date_posted|date:"d/m/Y" }}</span>
</div>
<div class="description item-description">
<p>{{ item.description }}</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
home.html
{% extends "selling/base.html" %}
{% load static %}
{% block content %}
<form action="{% url 'search' %}" method='get'>
{{ form }}
</form>
{% endblock content %}
settings.py - 已安装的应用
INSTALLED_APPS = [
'selling.apps.SellingConfig','users.apps.UsersConfig','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','django.contrib.postgres',]
urls.py
from django.urls import path
from .views import Search,HomepageView
urlpatterns = [
path('',HomepageView.as_view(),name='sell-home'),path('search/',Search.as_view(),name='search'),]
这就是全部代码。如果您需要其他任何东西,请随时询问。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。