如何为从下拉列表中选择的多个值编写Django过滤查询?

时间:2019-07-05 06:03:28

标签: python django django-views django-filter django-filters

我写了一个views函数,根据某些参数在django中搜索/过滤我的数据。用户可以在类别和位置字段中选择多个选项进行搜索。

我的视图功能如下:

def search(request):

    queryset_list = Influencer.objects.order_by('-followers').distinct().values('id',
                                                                'full_name','username','photo','email_id','location_city','categories__name','website')

    # Username
    if 'username' in request.GET:
        username = request.GET['username']
        if username:
            queryset_list = queryset_list.filter(username__icontains=username)

    #Full Name
    if 'fullname' in request.GET:
        fullname = request.GET['fullname']
        if fullname:
            queryset_list = queryset_list.filter(full_name__icontains=fullname)

    # Location
    if 'location' in request.GET:
        location = request.GET['location']
        for i in location:

            queryset_list = queryset_list.filter(location_city__icontains=i)

    # Categories
    if 'categories' in request.GET:
        categories = request.GET['categories']
        if categories:
            queryset_list = queryset_list.filter(categories__name__iexact=categories)

搜索功能应返回进行搜索的所有类别和位置的数据。例如如果搜索位置德里和孟买,则应返回所有位置为德里或孟买的有影响力者,同样也包括类别。

搜索功能非常适合单个值,但不适用于多个值。例如,如果在位置类别中发送了德里,则返回正确的结果,但如果选择了德里,孟买,则仅读取第一个值,即德里,并相应地应用过滤器。

如何修改搜索查询以使其正常工作?

3 个答案:

答案 0 :(得分:1)

我认为最简单的方法就是使用Q

 from django.db.models import Q
    q = request.GET.get('q')
    if q:
    queryset_list = queryset_list.filter(Q(username__icontains=q)|Q(full_name__icontains=q)|
    Q(location_city__icontains=q)|Q(categories__name__iexact=q))
    return render(....
    else:
        messages.info(request,'no results found for {}',format(q))

在您的模板中,在搜索表单中使用name=q

  <form  action="{% url 'your search action' %}">
     <input type="text" name="q">
     <input type='submit' value='Search'>
   </form>

,您可以将这样的all_queries与您的解决方案结合起来:

all_queries = username_queryset_list|fullname_queryset_list|location_queryset_list|
categories_queryset_list

答案 1 :(得分:0)

您是否为此目的使用过django-filterset?

class InfluencerFilter(filters.FilterSet):
username = filters.CharFilter(name='username', lookup_expr='iexact')
fullname = filters.CharFilter(name='fullname', lookup_expr='iexact')
location = filters.NumberFilter(name='location', lookup_expr='exact')
categories = filters.CharFilter(name='categories', lookup_expr='exact')


class Meta:
    model = Influencer
    fields = ['username','fullname','location','categories']

然后在您的视图中,可以使用以下命令调用此过滤器:

filter_backends = (filters.DjangoFilterBackend,)
filter_class = InfluencerFilter

这将使您免于所有烦人和多余的if语句,并且仅适用于可用的查询参数,而忽略其余参数。

答案 2 :(得分:0)

这是我对帐户进行搜索的方式:可能的搜索条件为自由文本(search_value),从选择框(sel_group)中选择组,仅选中活动中的复选框(chk_active)

    def post(self, request, *args, **kwargs):
        search_value = request.POST.get('searchValue', None)
        sel_group = request.POST.get('selGroup', 'ALL')
        chk_active = request.POST.get('chkActive', 0)

        filters = Q()
        if chk_active == '1':
            filters = filters & Q(is_active=True)
        if sel_group != 'ALL':
            filters = filters & Q(involvements__group__pk=sel_group)

        search_value = None if (search_value == '' or len(search_value) < 3) else search_value
        if search_value is not None:
            filters = filters & Q(last_name__icontains=search_value) | Q(first_name__icontains=search_value) | Q(email__icontains=search_value)

        users = get_user_model().objects.filter(filters)

        context = self.get_context_data(object_list=users)
        return render(request, template_name=self.template_name, context=context)

希望这会有所帮助;)