How to print a model object properly in Django?

Question:

I am new in django, I want to print my data, i am using this function to get data from table, page_data = Pages.objects.all().filter(id=id), i am getting this response <QuerySet [<Pages: Page 567>]>, why it shows only title column data ? It should show all the data, can anyone plese help me to show all the data whitin the table with print in cmd ?

enter image description here

Asked By: Nikul Panchal

||

Answers:

You can see each property data by accessing using the property name like

page_data.id 
page_data.title

By default the the query set will display only the primary key of the record as a tag for the query set which is why you see the id value 567 in [<Pages: Page 567>]

Answered By: Manu mathew

Perhaps you should be looking at overriding __str__() method to return whatever data you want from an object in Django Model.

Here you go.

https://docs.djangoproject.com/en/2.2/ref/models/instances/#str

You can also get any column value of the object using the below format.

object_name.column1_name

object_name.column2_name
Answered By: Underoos

To get a dictionary representation of a Django model object, you can access the __dict__ attribute:

model_object = Pages.objects.all().filter(id=id).first()
print(model_object.__dict__)

As a bonus, to do a colorized pretty print (e.g. in the ./manage.py shell REPL environment):

>>> from rich import pretty, print
>>> pretty.install()
>>> model_object.__dict__
Answered By: ddelange
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.