How to add filters to a query dynamically in Django?

后端 未结 6 479
半阙折子戏
半阙折子戏 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:38

    You haven't shown any code, so you haven't really explained what the problem is:

    Start with the queryset Book.objects.all(). For each filter, check if there is a value for the filter in request.POST, and if so, filter the queryset. Django querysets are lazy, so only the final queryset will be evaluated.

    queryset = Book.objects.all()
    if request.POST.get('age'):
        queryset = queryset.filter(author__age=request.POST['age'])
    if request.POST.get('gender'):
        queryset = queryset.filter(author__gender=request.POST['gender'])
    ...
    

提交回复
热议问题