使用字符串而不是点语法访问Django模型的字段? [英] Access Django model's fields using a string instead of dot syntax?

查看:119
本文介绍了使用字符串而不是点语法访问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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆