Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing all records with all the attributes

I am from PHP background and very new to Django.

I just want to see all the records with it's values for that I have write below code

Model file :

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

View file:

q = Question.objects.all()
    print(q)

In console it only outputs question_text. How can I print all the records with all the attributes.

like image 220
Paritosh Mahale Avatar asked Oct 14 '25 20:10

Paritosh Mahale


2 Answers

You can use of the model_to_dict function to obtain a dictionary from a model object:

import json
from django.forms.models import model_to_dict

qs = Question.objects.all()
for q in qs:
    print(json.dumps(model_to_dict(q), indent=2))
like image 168
Willem Van Onsem Avatar answered Oct 17 '25 13:10

Willem Van Onsem


There are two ways to do it ::
- Serialize in some format and show in json/xml
- just print the values for debugging purpose

The First way :-

You have to serialize the query set since the returned are of object type in your view Files. You have to add a serialize class so that the returned object will be converted to your desired format(for json or xml format).

from django.core import serializers    
data = serializers.serialize('xml/json', Question.objects.all(), fields=('name','size',....etc which you need))    print(data) It will print the data in either json or xml format.....

The Second way :-

or, simply run the below code :

p.values()
# <QuerySet [{'first_name': 'Linus', 'last_name': 'Torvalds', 'software_name': 'Linux'}]>
like image 39
abhikumar22 Avatar answered Oct 17 '25 13:10

abhikumar22



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!