使用字符串而不是点语法访问 Django 模型的字段? [英] Access Django model's fields using a string instead of dot syntax?
本文介绍了使用字符串而不是点语法访问 Django 模型的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Django 中,我可以这样做:
In Django, I can do this:
test = Test.objects.get(id=1)
test.name
我希望能够使用动态生成的字符串访问属性,如下所示:
I want to be able to access the properties using dynamically generated strings, like this:
test['name']
或者,使用字符串的任何其他语法.我试过了
or, any other syntax using a string. I tried
test._meta.get_field_by_name('name')
但这会返回字段本身而不是值.
but this returns the field itself and not the value.
有什么想法吗?
推荐答案
你可以使用 python 内置的 getattr()
函数:
You can use python's built in getattr()
function:
getattr(test, 'name')
这篇关于使用字符串而不是点语法访问 Django 模型的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文