django 查询集未显示准确结果(构建新闻应用程序)

Posted

技术标签:

【中文标题】django 查询集未显示准确结果(构建新闻应用程序)【英文标题】:django queryset not showing accurate result (building a news app) 【发布时间】:2021-04-04 00:50:39 【问题描述】:

我正在使用 django 创建一个新闻应用程序。它包括按日期搜索选项。当我选择日期(例如:29-11-2020)并单击提交时,它应该带我查看当天的新闻。当我尝试下面的代码而不是显示详细信息时,它给了我一个空白页。 视图.py

from django.shortcuts import render
from .models import *
from django.views.generic.detail import DetailView
from django.views.generic import ListView

def index(request):
    return render(request,'newspaperapp/index.html')

class nowlist(ListView):
     model = newsmodel_1
     template_name = 'newspaperapp/index.html'

class newslist(DetailView):
    model = newsmodel_1
    template_name = 'newspaperapp/home.html'
    context_object_name = 'newspaperapp'

# search by giving date in index and search date
class SearchView(ListView):
     model = newsmodel_1
     template_name = 'newspaperapp/search.html'
     context_object_name = 'all_search_results'

def get_queryset(self):
    result = super(SearchView, self).get_queryset()
    query = self.request.GET.get('search')
    if query:
         postresult = newsmodel_1.objects.filter(date_published__contains=query)
             result = postresult
        else:
            result = None
        return result

urls.py

from django.urls import path
app_name = 'newspaperapp'
from .views import newslist,SearchView,nowlist
from newspaperapp import views
urlpatterns = [
     path('',views.index,name='index'),
     path('date/',nowlist.as_view(),name = "date"),
     path('<int:pk>',newslist.as_view(),name = "home"),
     path('results/', SearchView.as_view(), name='search'),
     ]

newspaperapp/home.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>
    <p>Today's Paper</p>
    newspaperapp.date_published
    newspaperapp.category
 </body>

newspaperapp/index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
   <meta charset="utf-8">
 <title></title>
 </head>
 <body>
 <!-- this page has search option and different categories of news -->
 <!-- to create search option we write views code and continue -->
 <form class="form-inline my-2 my-lg-0" method="GET" action="% url 'newspaperapp:search' %">
 <input class="form-control mr-sm-2" type="date" placeholder="Search" aria-label="Search" 
  name="search">
 <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
 </form>

%for newspaperapp in object_list %
<li><a href="%url 'newspaperapp:home' newspaperapp.pk %">newspaperapp.title</a>
 newspaperapp.date_published
 %endfor%
</ul>

</body>
</html>

newspaperapp/search.html

% block content %
% for newspaperapp in all_search_results %
    <h3><a href="%url 'newspaperapp:home' newspaperapp.pk %"></a></h3>
% empty %
    <h2>No results found</h2>
% endfor %
% endblock %

【问题讨论】:

您的输入没有 name="search" 属性,因此它不会被发送,它会导致您的结果为 None (检查您的 if 条件) 【参考方案1】:

Contain在sql中通常翻译为LIKE,通常用于在列中搜索指定的文本模式

如果要过滤日期,可以将query 转换为日期时间对象,并使用gtelt 搜索特定日期范围内的对象strong> 查找。

from datetime import datetime, timedelta

class SearchView(ListView):
    model = newsmodel_1
    template_name = 'newspaperapp/search.html'
    context_object_name = 'all_search_results'

    def get_queryset(self):
        result = super(SearchView, self).get_queryset()
        query = self.request.GET.get('search')
        # query is of type 'str', convert to datetime
        start_day = datetime.fromisoformat(query)
        end_day   = start_day + timedelta(days=1)
        if query:
             postresult = newsmodel_1.objects.filter(
                 date_published__gte=start_day, 
                 date_published__lt=end_day
             )
             result = postresult
        else:
            result = None
        return result

注意:添加更多逻辑来处理queryNone

【讨论】:

还是一样的结果。 @PadalaKavya 忘记了&lt;a&gt; 标签中的项目? &lt;h3&gt;&lt;a href="%url 'newspaperapp:home' newspaperapp.pk %"&gt; newspaperapp &lt;/a&gt;&lt;/h3&gt;,也尝试打印postresult 以查看查询集是否正确传递 我其实想在点击搜索后直接进入详细信息页面,但上面的代码将我带到详细信息页面的链接。我该如何解决这个问题?请帮忙

以上是关于django 查询集未显示准确结果(构建新闻应用程序)的主要内容,如果未能解决你的问题,请参考以下文章

用于构建“新闻提要”/“状态更新”/“活动流”的 Django 方式

连接关闭时结果集未关闭?

连接关闭时结果集未关闭?

结果集未打开。不允许操作“getString”。验证自动提交是不是关闭。?

如何使用 Django Rest 过滤器限制查询结果

Django - 显示结果信息,同时使用具有多个外键关系的模型优化数据库查询