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.
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())
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'}]>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With