Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method in Django to display all attributes' values belonging to a created object?

Is there a certain method in Django which allows for retrieving/displaying all attributes' values belonging to an object created via Django?

In Python shell, I used the following:

>>> print(p.first_name, p.last_name, p.software_name)
Linus Torvalds Linux

p is the created object with the attributes first_name, last_name, software_name. I already created several models which were applied to a specific database in mysql.

I would like to learn of other ways to display such information.

like image 525
aspiring Avatar asked Jan 06 '18 20:01

aspiring


Video Answer


2 Answers

The Python built-in special attribute object.__dict__ can retrieve all the attributes of the object, as a dictionary.

p.__dict__
# returns {'first_name': 'Linus', 'last_name': 'Torvalds', 'software_name': 'Linux'}

Alternatively, use the Python built-in function vars(), which returns the __dict__ of the object, giving the same result.

vars(p)

For a QuerySet, you may consider displaying the attributes of one of the QuerySet items, e.g.:

q.first().__dict__
# or
vars(q.first())
like image 126
yhd.leung Avatar answered Oct 19 '22 18:10

yhd.leung


A bit late, but as none of the answers mentioned the easiest way to do that:

>>> # assuming your object was already saved in the database and p is the QuerySet
>>> # with your object
>>> p.values()
<QuerySet [{'first_name': 'Linus', 'last_name': 'Torvalds', 'software_name': 'Linux'}]>
like image 33
arudzinska Avatar answered Oct 19 '22 18:10

arudzinska