我试图将一个参数传递给一个带有键的方法来获取Django查询集。密钥取决于用户通过的内容。
以下是一个例子:
filter的初始值将是id = 1(一个字符串),如果用户传入其他过滤器,我会包含基于逗号的分割,例如title = blahblahblah
filter_split = filters.split(",")
itemFilter = Items.objects # from Django
for f in filter_split:
itemFilter = itemFilter.filter(f)
我还尝试将剩余的字符串拆分为两个单独的值(键和值)并按原样传递它们:
itemFilter = itemFilter.filter(key = value)
没有运气。
如何将编程参数传递给Python中的方法?或者是否有另一种方法以Django以编程方式过滤查询集?
答案 0 :(得分:1)
传递字符串是不可能的,例如"id=1"
来过滤。
您可以动态创建字典,然后使用**解包将其传递给过滤器。
key = "id"
value = 1
kwargs = {key: value}
MyModel.objects.filter(**kwargs)
尝试MyModel.objects.filter(key=value)
的其他方法不起作用,因为它不使用变量键,它会尝试过滤字段'key'
答案 1 :(得分:1)
您可以在参数列表中使用[1] Original app was compiled into a jar file, the jar file was doing copy-paste correctly either direction
[2] But the jar file can't be pined to the taskbar
[3] So I used exe4j to compile it into an exe file to be able to pin to the tackbar
[4] The result exe file can't do copy-paste correctly [ exe4j issue ]
[5] I found a way to pin jar file to the taskbar through a javaw.exe -jar *.jar shortcut,and pin that shortcut to the taskbar
和*list
传递编程参数。
**dict
在您的情况下,只需创建一个字典,从用户输入中分配键值对并调用a = [2,3,4]
function(1, *a) # equal to function(1,2,3,4)
b = {'x':42, 'y':None}
function(1, **b) # equal to function(1, x=42, y=None)
。