[Django] Convert QuerySet to dictionary type list

Introduction

I wanted to convert the data obtained from the model to a list with a QuerySet → dict element and do various things, but unexpectedly the information did not come out immediately, so I will post it.

Conclusion

The following is OK.

from .models import Choice

choice_query_set = Choice.objects.all() #Get all records with QuerySet type
choice_list = list(choice_query_set.values())
print(choice_list)
#[{'id': 1, 'question_id': 1, 'choice_text': 'test1', 'votes': 3}, {'id': 2, 'question_id': 1, 'choice_text': 'test2', 'votes': 1}, {'id': 3, 'question_id': 1, 'choice_text': 'test3', 'votes': 2}]

Commentary

from .models import Choice

choice_query_set = Choice.objects.all()
print(choice_query_set)  #Get with QuerySet
#<QuerySet [<Choice: test1>, <Choice: test2>, <Choice: test3>]>

print(choice_query_set.values())  #Conversion 1
#<QuerySet [{'id': 1, 'question_id': 1, 'choice_text': 'test1', 'votes': 3}, {'id': 2, 'question_id': 1, 'choice_text': 'test2', 'votes': 1}, {'id': 3, 'question_id': 1, 'choice_text': 'test3', 'votes': 2}]>

print(list(choice_query_set.values()))  #Conversion 2
#[{'id': 1, 'question_id': 1, 'choice_text': 'test1', 'votes': 3}, {'id': 2, 'question_id': 1, 'choice_text': 'test2', 'votes': 1}, {'id': 3, 'question_id': 1, 'choice_text': 'test3', 'votes': 2}]

Conversion 1: Choice_query_set .values () </ font> expands each element (Choice object) of QuerySet to dict type </ font> Conversion 2: Convert QuerySet to list with list (</ font> choice_query_set.values () ) </ font> / font>

that's all. Once you know it, it's nothing: cat2:

Recommended Posts