17👍
Assuming name is an attribute on your instance test getattr(test, 'name')
should return the corresponding value. Or test.__dict__['name']
.
You can read more about getattr()
here: http://effbot.org/zone/python-getattr.htm
👤arie
- [Django]-Convert Django Model object to dict with all of the fields intact
- [Django]-CSV new-line character seen in unquoted field error
- [Django]-How to use Django ImageField, and why use it at all?
15👍
Other answers still stand, but now you can do this using Django’s _meta.get_field().
test._meta.get_field('name')
Note that the Model _meta API has begun its official support and documentation as of 1.8, but has been distributed and used in prior versions before its official documentation.
- [Django]-How can I get tox and poetry to work together to support testing multiple versions of a Python dependency?
- [Django]-Django FileField with upload_to determined at runtime
- [Django]-What is the best location to put templates in django project?
6👍
In Python, you can normally access values within an object that has a dict method.
Let’s say you have this class:
class Dog(object):
def __init___(self, color):
self.color = color
And then I instantiate it:
dog = Dog('brown')
So i can see the color by doing:
print dog.color
I can also see the color by doing:
print dog.__dict__['color']
I can set the color:
print dog.__dict__['color'] = 'green'
print dog.color
>>>green
- [Django]-In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected?
- [Django]-Update only specific fields in a models.Model
- [Django]-Constructing Django filter queries dynamically with args and kwargs
Source:stackexchange.com