为什么在我的Django视图中查询“ green”或“ bay”时,查询“ green bay”不起作用?

时间:2019-11-11 01:14:46

标签: python django python-3.x django-models django-views

这是我的观点:

def search(request):
    if request.method == 'GET':
        try:
            q = request.GET.get('search_box', None)
            s_or_l = request.GET.get('s_or_l', None)
            p_class = request.GET.get('p_class', None)
            if p_class:
                posts = Listing.objects.filter(title__contains=q, is_live=1, sale_or_lease=s_or_l,
                                               property_class=p_class) | \
                        Listing.objects.filter(street_address__contains=q, is_live=1, sale_or_lease=s_or_l,
                                               property_class=p_class) | \
                        Listing.objects.filter(city__contains=q, is_live=1, sale_or_lease=s_or_l,
                                               property_class=p_class) | \
                        Listing.objects.filter(state__contains=q, is_live=1, sale_or_lease=s_or_l,
                                               property_class=p_class)
            else:
                posts = Listing.objects.filter(title__contains=q, is_live=1, sale_or_lease=s_or_l) | \
                        Listing.objects.filter(street_address__contains=q, is_live=1, sale_or_lease=s_or_l) | \
                        Listing.objects.filter(city__contains=q, is_live=1, sale_or_lease=s_or_l) | \
                        Listing.objects.filter(state__contains=q, is_live=1, sale_or_lease=s_or_l)
            return render(request, 'search/results.html', {'posts': posts, 'q': q})
        except KeyError:
            return redirect('home')

对于将city设置为“绿湾”的财产,以下搜索将按预期进行:

green

bay

Green Bay

但是green bay <-不起作用。为什么是这样?我该如何解决?

为什么只有空格时才区分大小写?

1 个答案:

答案 0 :(得分:1)

使用icontains代替contains进行案例搜索

Listing.objects.filter(city__icontains=q, is_live=1, sale_or_lease=s_or_l)

关于greenbayGreen Bay为何起作用但为何green bay无效的原因,我认为单独的术语greenbay来了小写的其他地方,可能在您的标题或街道地址中。

除非您使用contains,否则用green过滤bayGreen Bay绝不会返回icontains