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

Django中如何通过函数传入的变量访问模型对应属性?

问题:通过变量字符串访问Django模型属性

我编写了一个自定义函数,希望通过传入的模型属性名称参数获取对应数值,代码如下:

def tabsums(entity_object, year_object, columntitle):
    curassetobject = BSAccountType.objects.get(name = "Current asset", company = entity_object)
    curassetsum = BSSum.objects.get(Q(company = entity_object) & Q(year = year_object) & Q(account_type = curassetobject)).columntitle

当前的问题是,Python/Django会直接寻找名为columntitle的属性(该属性不存在),而非使用columntitle变量对应的字符串值作为属性名来取值。请问有没有语法可以实现利用传入变量的字符串值访问模型属性?


解答

可以使用Python内置的getattr()函数实现这个需求,它的作用就是通过字符串形式的名称获取对象的属性值。

修改后的代码如下:

def tabsums(entity_object, year_object, columntitle):
    curassetobject = BSAccountType.objects.get(name="Current asset", company=entity_object)
    # 先获取BSSum的实例对象
    bs_sum_instance = BSSum.objects.get(Q(company=entity_object) & Q(year=year_object) & Q(account_type=curassetobject))
    # 用getattr通过字符串变量获取对应属性值
    curassetsum = getattr(bs_sum_instance, columntitle)

如果需要避免因传入的属性名称不存在而抛出AttributeError,可以给getattr()添加第三个参数作为默认值:

curassetsum = getattr(bs_sum_instance, columntitle, None)

这样当属性不存在时,会返回None(你也可以替换成其他适合的默认值)。


内容的提问来源于stack exchange,提问作者eb123456

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:05:35