How to add filters to a query dynamically in Django?

后端 未结 6 493
半阙折子戏
半阙折子戏 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条回答
  •  猫巷女王i
    2021-02-06 10:39

    Maybe django-filter would help simplify the solutions others have given?

    Something like:

    class BookFilter(django_filters.FilterSet):
        class Meta:
            model = Book
            fields = ['author__age', 'author__gender', ...]
    

    Then the view looks like:

    def book_list(request):
        f = BookFilter(request.GET, queryset=Book.objects.all())
        return render_to_response('my_app/template.html', {'filter': f})
    

    For more information see the documentation.

提交回复
热议问题