How to add filters to a query dynamically in Django?

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

    You can simply get the request.GET content as a dict (making sure to convert the values to string or a desired type as they'd be list by default i.e: dict(request.GET) would give you something like {u'a': [u'val']}.

    Once you are sure you have a dictionary of keys matching your model fields, you can simply do:

    filtered = queryset.filter(**dict_container)

提交回复
热议问题