当我尝试在没有搜索查询的情况下查看页面时,无法使用 None 作为查询值错误

Cannot use None as a query value error when i try to view page without search query

我的 base.html 中有一个可用的搜索表单,但是当我尝试访问列表页面而不通过搜索查询时,我收到“无法使用 None 作为查询值”错误。 views.py

def listing(request):

        if request.method == 'GET':
            search =  request.GET.get('search')       
            propertys = Paginator(Property.objects.filter(property_name__icontains =search).order_by('-listed_on'), 2)
            page = request.GET.get('page')
            propertys = propertys.get_page(page)
            nums = "p" * propertys.paginator.num_pages
            return render(request,"listing.html",{"propertys":propertys, "nums": nums, 'search':search})
        else:
            p = Paginator(Property.objects.order_by('-listed_on'), 2)
            page = request.GET.get('page')
            propertys = p.get_page(page)
            nums = "p" * propertys.paginator.num_pages
            return render(request,"listing.html", {"propertys":propertys, "nums": nums})

您不能以这种方式搜索 None,但您可以在实际尝试之前先检查 search 是否具有 None 以外的值:

替换

propertys = Paginator(Property.objects.filter(property_name__icontains =search).order_by('-listed_on'), 2)

if search:
    propertys = Paginator(Property.objects.filter(property_name__icontains =search).order_by('-listed_on'), 2)