How to add filters to a query dynamically in Django?

后端 未结 6 480
半阙折子戏
半阙折子戏 2021-02-06 09:56

In my viewSet I am doing a query,

queryset= Books.objects.all();

Now from an ajax call I get my filter values from UI i.e. age,gender, etc. of

6条回答
  •  生来不讨喜
    2021-02-06 10:42

    Here's a bit more generic one. It will apply filters to your queryset if they are passed as the GET parameters. If you're doing a POST call, just change the name in the code.

    import operator
    from django.db.models import Q
    
    
    def your_view(self, request, *args, **kwargs):
        # Here you list all your filter names
        filter_names = ('filter_one', 'filter_two', 'another_one', )
    
        queryset = Books.objects.all(); 
        filter_clauses = [Q(filter=request.GET[filter])
                          for filter in filter_names
                          if request.GET.get(filter)]
        if filter_clauses:
            queryset = queryset.filter(reduce(operator.and_, filter_clauses))
    
        # rest of your view
    

    Note that you can use lookup expressions in your filters' names. For example, if you want to filter books with price lower or equal to specified in filter, you could just use price__lte as a filter name.

提交回复
热议问题