[PYTHON] [Django] Abfragesatz konvertieren, um Typliste zu diktieren

Einführung

Ich wollte die vom Modell erhaltenen Daten in eine Liste mit einem QuerySet → dict-Element konvertieren und verschiedene Dinge tun, aber unerwartet kamen die Informationen nicht sofort heraus, also werde ich sie veröffentlichen.

Fazit

Folgendes ist in Ordnung.

from .models import Choice

choice_query_set = Choice.objects.all() #Ruft alle Datensätze mit dem QuerySet-Typ ab
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}]

Kommentar

from .models import Choice

choice_query_set = Choice.objects.all()
print(choice_query_set)  #Holen Sie sich mit QuerySet
#<QuerySet [<Choice: test1>, <Choice: test2>, <Choice: test3>]>

print(choice_query_set.values())  #Konvertierung 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()))  #Konvertierung 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}]

Konvertierung 1: choice_query_set .values () </ font> erweitert jedes Element (Choice-Objekt) von QuerySet, um den Typ </ font> zu bestimmen Konvertierung 2: Konvertieren Sie QuerySet in eine Liste mit Liste (</ font> choice_query_set.values () ) </ font> / font>

das ist alles. Sobald Sie es wissen, ist es nichts: cat2:

Recommended Posts