如何通过动态路径实现Django模型对象列表过滤?
Got it, let's work through this—you want to use a string-based field lookup (like "pk__in") dynamically in a Django ORM filter, right? The problem with your original code is that when you write filter(path=resource_ids), Django treats path as a literal field name instead of using the value stored in your path variable. Here's the straightforward fix:
The Solution: Dictionary Unpacking
Instead of passing the lookup directly as a keyword argument, create a dictionary where the key is your dynamic lookup string, and the value is the filter criteria. Then use the ** operator to unpack this dictionary into keyword arguments for the filter() method.
Here's your corrected code:
path = "pk__in" # Build a dictionary with the dynamic lookup as the key filter_params = {path: resource_ids} # Unpack the dictionary to pass the lookup as a keyword argument resources = resource_model.objects.filter(**filter_params)
Why This Works
Django's QuerySet.filter() accepts keyword arguments where each key maps to a field lookup (like pk__in). When your lookup is stored in a string variable, you can't use it directly as a keyword argument name—instead, the ** syntax tells Python to take the key-value pairs from the dictionary and pass them exactly as if you had written filter(pk__in=resource_ids) manually.
Bonus: Handling Multiple Dynamic Lookups
If you ever need to add more dynamic filters later, just expand the dictionary with additional key-value pairs:
lookup1 = "name__contains" value1 = "sample" lookup2 = "status__exact" value2 = "active" filter_params = { lookup1: value1, lookup2: value2 } resources = resource_model.objects.filter(**filter_params)
This approach is perfect for cases where your filter conditions are generated dynamically—like from user input, configuration files, or runtime logic.
内容的提问来源于stack exchange,提问作者Sprookd

