Django QuerySet Filtering with Conditions from a List of Dictionaries - implementing Q Objects
This might be a silly question, but I tried several approaches but none seem to work. Hey everyone, I'm running into an issue that's driving me crazy... After trying multiple solutions online, I still can't figure this out... I'm trying to filter a Django QuerySet based on dynamic conditions that I have in a list of dictionaries, where each dictionary contains field names and their corresponding values. However, I'm running into issues when building the query using `Q` objects. In my case, I have a list like this: ```python conditions = [ {'field_name': 'status', 'value': 'active'}, {'field_name': 'category', 'value': 'electronics'}, {'field_name': 'price__lt', 'value': 1000} ] ``` I want to construct a single QuerySet that matches all these conditions. Initially, I attempted to use a loop with `Q` objects like this: ```python from django.db.models import Q query = Q() for condition in conditions: query &= Q(**{condition['field_name']: condition['value']}) ``` However, when I execute this query against a model, like `Product`, using `Product.objects.filter(query)`, I'm getting an behavior: `TypeError: 'Q' object is not subscriptable`. I suspect my use of `Q` objects may not be correct, but I'm unsure how to structure it properly. I’ve also tried using `reduce` from `functools`, but I still face issues. Can someone guide to figure out how to correctly build this dynamic query? I'm using Django 3.2.4 and Python 3.8.10. This is part of a larger application I'm building. Any ideas what could be causing this? Am I missing something obvious? What would be the recommended way to handle this? This is part of a larger application I'm building. What are your experiences with this?