Django 对象获取/设置字段 [英] django object get/set field
本文介绍了Django 对象获取/设置字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是否可以通过 obj.field
以外的其他方式获取对象字段的值?像 obj.get('field')
这样的东西存在吗?设置字段的值也是如此.
Can I get the value of an object field some other way than obj.field
? Does something like obj.get('field')
exist? Same thing for setting the value of the field.
推荐答案
获取字段的值:
getattr(obj, 'field_name')
设置字段的值:
setattr(obj, 'field_name', 'field value')
获取 Django 对象的所有字段和值:
To get all the fields and values for a Django object:
[(field.name, getattr(obj,field.name)) for field in obj._meta.fields]
您可以阅读 Model _meta API 的文档,它是很有用.
You can read the documentation of Model _meta API which is really useful.
这篇关于Django 对象获取/设置字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文