[Fixed]-Method in Django to display all attributes' values belonging to a created object?

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())
πŸ‘€yhd.leung

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'}]>
πŸ‘€arudzinska

6πŸ‘

Try using the inbuilt python dir() method

dir(object)

πŸ‘€Xerrex

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
πŸ‘€eneski

-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.

Leave a comment