首页 > 解决方案 > Django ORM 添加变量而不是 .filter 指令

问题描述

在我的项目中,我有一个带有 django ORM 查询的函数。我会将传递给函数的值列表传递给 .filter 部分:

def testFilter(filterlist):
    #for example filterlist could be: thread='DEAD',id=11,t_type='SA'
     myquery = t_threads.objects.filter(filterlist).select_related().order_by(lorder)[x:y]

但如果我,例如运行我的功能:

testFilter("id=1,thread='LIVE'")

我有一个错误:

ValueError:要解包的值太多(预期为 2)

每次运行该函数时,如何通过过滤器指令运行我的 ORM 查询?

非常感谢提前

标签: djangopython-3.xorm

解决方案


您应该kwargs为此使用:

def testFilter(**kwargs):
     myquery = t_threads.objects.filter(**kwargs)...

testFilter(id=1, thread='LIVE')

推荐阅读