24π
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())
22π
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'}]>
- Django runserver custom database
- How to have a link in label of a form field
- Exclude field from values() or values_list()
- Django. Error message for login form
- Python multiple inheritance function overriding and ListView in django
1π
You can define __str__
method for the corresponding model class, like in the following.
class User(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
software_name = models.CharField(max_length=100)
def __str__(self):
return self.first_name + " " + self.last_name + " " + self.software_name
You can achieve your desire like following on django Shell, assuming your first entry is Linus Torvalds Linux in your database.
from main_app.models import User
e = User.objects.get(pk=1)
e
- Django AttributeError 'tuple' object has no attribute 'regex'
- Django 2.0: sqlite IntegrityError: FOREIGN KEY constraint failed
- Django 1.7 upgrade error: AppRegistryNotReady: Models aren't loaded yet
-1π
There is model_to_dict function you can use. Check this answer.
This module packages it as a mixin : django-model-to-dict
Once your object is in dictionary form, a print or any processing should be easier.