You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过动态路径实现Django模型对象列表过滤?

Dynamic Field Lookups with Django ORM

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 13:57:40