Search code examples
djangofiltermodels

Django Model filters on the basis of query string


I want to filter queries and I want to create filters on the basis of my query string.

for example:

if request.GET.get('color'):
   #filter result set on the basis of color
if request.GET.get('price'):
   #filter result set on the basis of specified price
if request.GET.get('category'):
   #filter result set on the basis category

How can we do this efficiently in django. I have more than 2 Million records in my database.


Solution

  • It can be done like this:

    products = Product.objects.all()
    for filter_field in ('color', 'price', 'category'):
        if request.GET.get(filter_field):
            products = products.filter(**{filter_field: request.GET[filter_field]})
    

    Efficiency of that construction depends only on your database structure, on indexes that you have in DB. Cause django doesn't execute queries before return. It constructs one SQL query as result.