25
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Django】QuerySetを辞書型(dict)のlistに変換する

Posted at

#はじめに
modelから取得したデータをQuerySet→dict要素を持つlistに変換してあれこれしたかったのですが、意外とすぐに情報が出てこなかったので投稿します。

#結論
以下でOKです。

from .models import Choice

choice_query_set = Choice.objects.all() #QuerySet型で全件取得
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}]

#解説

from .models import Choice

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

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

変換1:choice_query_set.values()QuerySetが持つ各要素(Choiceオブジェクト)をdict型に展開
変換2:list(choice_query_set.values())QuerySetからlistに変換

以上です。
知ってしまえばなんてことないですね:cat2:

25
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?