Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python(Django)中使用名称属性作为参数_Python_Django - Fatal编程技术网

在Python(Django)中使用名称属性作为参数

在Python(Django)中使用名称属性作为参数,python,django,Python,Django,我试图在函数中将name属性作为参数传递,以使其更通用 例如,我想修改此函数: @classmethod def count_events_per_day(cls, myqueryset): return myqueryset.filter( created__range=(a,b)) 制作类似于: @classmethod def count_events_per_day(cls, myqueryset, attr_name): # attr_name would b

我试图在函数中将name属性作为参数传递,以使其更通用

例如,我想修改此函数:

@classmethod
def count_events_per_day(cls, myqueryset):
    return myqueryset.filter(
        created__range=(a,b))
制作类似于:

@classmethod
def count_events_per_day(cls, myqueryset, attr_name): # attr_name would be passed as a string
    return myqueryset.filter(
        attr_name__range=(a,b))
有办法做到这一点吗? 我继续搜索,但我想我使用的关键词是不相关的,因为我找不到任何答案


谢谢

这很简单,因为您可以从字典向函数传递参数:

@classmethod
def count_events_per_day(cls, myqueryset, attr_name):
    return myqueryset.filter(**{
        attr_name + '__range': (a, b)
    })

UPD:添加带有双星语法解释的答案链接:

这将创建一个
语法错误:关键字不能是表达式
:(@DavidW.作为attr_name传递什么?
'created'
attr_name
恐怕不是字符串。啊,是的,我当然传递字符串。我只是想说attr在Django上下文中不是字符串。抱歉。顺便说一句,它似乎有效,但我不明白如何继续测试某些内容,然后返回!谢谢:)@DavidW.当然。其他人已经解释过了,我只是添加了链接。恐怕我不明白。所以你想自动修改属性名?@GamesBrainiac就是这样。因为我需要对不同的属性使用此方法(而不仅仅是
创建的
),我希望避免为我拥有的N个属性编写N次此方法。attr\u name是什么类型?它只是一个字符串吗?@GamesBrainiac Nope。它是一个对象的属性。我的类是
Event
,它的一个属性是
created
@DavidW。您能告诉我们如何调用
count\u events\u per\u day
,以及它是什么吗参数的值?为什么不能将
'created'
作为
attr\u name
传递?