Djangoのクエリセットから値を取得する方法

Djangoのクエリセットから値を取得する方法をご紹介します。

条件

  • Django 2.1.4
  • Python 3.7.0

前提

モデル

以下のようなモデルが定義されているとします。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Location(models.Model):
"""場所モデル"""
class Meta:
db_table = 'location'
name = models.CharField(verbose_name='ロケーション名', max_length=255)
memo = models.CharField(verbose_name='メモ', max_length=255, default='', blank=True)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
created_at = models.DateTimeField(verbose_name='登録日時', auto_now_add=True)
updated_at = models.DateTimeField(verbose_name='更新日時', auto_now=True)
def __str__(self):
return self.name
class Location(models.Model): """場所モデル""" class Meta: db_table = 'location' name = models.CharField(verbose_name='ロケーション名', max_length=255) memo = models.CharField(verbose_name='メモ', max_length=255, default='', blank=True) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) created_at = models.DateTimeField(verbose_name='登録日時', auto_now_add=True) updated_at = models.DateTimeField(verbose_name='更新日時', auto_now=True) def __str__(self): return self.name
class Location(models.Model):
    """場所モデル"""
    class Meta:
        db_table = 'location'

    name = models.CharField(verbose_name='ロケーション名', max_length=255)
    memo = models.CharField(verbose_name='メモ', max_length=255, default='', blank=True)
    author = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE,
    )
    created_at = models.DateTimeField(verbose_name='登録日時', auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name='更新日時', auto_now=True)

    def __str__(self):
        return self.name

データ

以下のようなデータがDBに存在するものとします。

クエリセットからの値取得

レコード1件を取得してカラム指定

  • ポイント
    • pkまたはidで指定します。
    • カラム名を指定して情報を取り出します。

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from monitor.models import Location
result = Location.objects.get(pk=1)
print('result = ' + result.name)
> result = 東京
from monitor.models import Location result = Location.objects.get(pk=1) print('result = ' + result.name) > result = 東京
from monitor.models import Location
result = Location.objects.get(pk=1)
print('result = ' + result.name)

> result = 東京
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from monitor.models import Location
result = Location.objects.get(id=1)
print('result = ' + result.name)
> result = 東京
from monitor.models import Location result = Location.objects.get(id=1) print('result = ' + result.name) > result = 東京
from monitor.models import Location
result = Location.objects.get(id=1)
print('result = ' + result.name)

> result = 東京

特定のカラム値を取得

  • ポイント
    • values_list() の引数の渡したフィールド値のタプルリストを返します。
    • flat = True とすると1要素のタプルではなく一つの値として返されます。

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result = Location.objects.values_list('name', flat=True).get(pk=1)
print('result = ' + result)
> result = 東京
result = Location.objects.values_list('name', flat=True).get(pk=1) print('result = ' + result) > result = 東京
result = Location.objects.values_list('name', flat=True).get(pk=1)
print('result = ' + result)

> result = 東京
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Location.objects.values_list('memo', flat=True).get(pk=2)
print('result = ' + result)
> result = 沖縄です。
Location.objects.values_list('memo', flat=True).get(pk=2) print('result = ' + result) > result = 沖縄です。
Location.objects.values_list('memo', flat=True).get(pk=2)
print('result = ' + result)

> result = 沖縄です。

参考:flat=Falseの場合

結果はタプルで返ります。

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result = Location.objects.values_list('name', flat=False).get(pk=1)
print('result = ' + result)
> result = ('東京',)
result = Location.objects.values_list('name', flat=False).get(pk=1) print('result = ' + result) > result = ('東京',)
result = Location.objects.values_list('name', flat=False).get(pk=1)
print('result = ' + result)

> result = ('東京',)
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Location.objects.values_list('memo', flat=False).get(pk=2)
print('result = ' + str(result))
> result = ('沖縄です。',)
Location.objects.values_list('memo', flat=False).get(pk=2) print('result = ' + str(result)) > result = ('沖縄です。',)
Location.objects.values_list('memo', flat=False).get(pk=2)
print('result = ' + str(result))

> result = ('沖縄です。',)

参考:flat=Falseで複数指定の場合

結果はタプルで返ります。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result = Location.objects.values_list('name', 'memo', 'created_at', flat=False).get(pk=1)
print('result = ' + str(result))
> result = ('東京', '東京です。', datetime.datetime(2018, 12, 19, 11, 57, 8, 856505))
result = Location.objects.values_list('name', 'memo', 'created_at', flat=False).get(pk=1) print('result = ' + str(result)) > result = ('東京', '東京です。', datetime.datetime(2018, 12, 19, 11, 57, 8, 856505))
result = Location.objects.values_list('name', 'memo', 'created_at', flat=False).get(pk=1)
print('result = ' + str(result))

> result = ('東京', '東京です。', datetime.datetime(2018, 12, 19, 11, 57, 8, 856505))

クエリセットからの値取得(辞書形式)

  • ポイント
    • values() の引数の渡したフィールド値の辞書リストを返します。

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result = Location.objects.values('name').get(pk=1)
print('result = ' + str(result))
print('result = ' + result.get('name'))
> result = {'name': '東京'}
> result = 東京
result = Location.objects.values('name').get(pk=1) print('result = ' + str(result)) print('result = ' + result.get('name')) > result = {'name': '東京'} > result = 東京
result = Location.objects.values('name').get(pk=1)
print('result = ' + str(result))
print('result = ' + result.get('name'))

> result = {'name': '東京'}
> result = 東京

参考:複数指定の場合

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result = Location.objects.values('name', 'memo').get(pk=2)
print('result = ' + str(result))
print('result = ' + result.get('name'))
print('result = ' + result.get('memo'))
> result = {'name': '沖縄', 'memo': '沖縄です。'}
> result = 沖縄
> result = 沖縄です。
result = Location.objects.values('name', 'memo').get(pk=2) print('result = ' + str(result)) print('result = ' + result.get('name')) print('result = ' + result.get('memo')) > result = {'name': '沖縄', 'memo': '沖縄です。'} > result = 沖縄 > result = 沖縄です。
result = Location.objects.values('name', 'memo').get(pk=2)
print('result = ' + str(result))
print('result = ' + result.get('name'))
print('result = ' + result.get('memo'))

> result = {'name': '沖縄', 'memo': '沖縄です。'}
> result = 沖縄
> result = 沖縄です。

すべての結果を取得

  • ポイント
    • QuerySetで返った結果をforループで値を取り出します。

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result = Location.objects.all()
print('result = ' + str(result))
for data in result:
print('name = ' + data.name)
print('memo = ' + data.memo)
print('created_at = ' + str(data.created_at))
> result = <QuerySet [<Location: 東京>, <Location: 沖縄>]>
> name = 東京
> memo = 東京です。
> created_at = 2018-12-19 11:57:08.856505
> name = 沖縄
> memo = 沖縄です。
> created_at = 2018-12-19 11:57:18.820476
result = Location.objects.all() print('result = ' + str(result)) for data in result: print('name = ' + data.name) print('memo = ' + data.memo) print('created_at = ' + str(data.created_at)) > result = <QuerySet [<Location: 東京>, <Location: 沖縄>]> > name = 東京 > memo = 東京です。 > created_at = 2018-12-19 11:57:08.856505 > name = 沖縄 > memo = 沖縄です。 > created_at = 2018-12-19 11:57:18.820476
result = Location.objects.all()
print('result = ' + str(result))
for data in result:
    print('name = ' + data.name)
    print('memo = ' + data.memo)
    print('created_at = ' + str(data.created_at))

> result = <QuerySet [<Location: 東京>, <Location: 沖縄>]>
> name = 東京
> memo = 東京です。
> created_at = 2018-12-19 11:57:08.856505
> name = 沖縄
> memo = 沖縄です。
> created_at = 2018-12-19 11:57:18.820476

参考:結果をタプルに変換

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result = Location.objects.all()
name = [data.name for data in result]
memo = [data.memo for data in result]
created_at = [data.created_at for data in result]
print('name = ' + str(name))
print('memo = ' + str(memo))
print('created_at = ' + str(created_at))
> name = ['東京', '沖縄']
> memo = ['東京です。', '沖縄です。']
> created_at = [datetime.datetime(2018, 12, 19, 11, 57, 8, 856505), datetime.datetime(2018, 12, 19, 11, 57, 18, 820476)]
result = Location.objects.all() name = [data.name for data in result] memo = [data.memo for data in result] created_at = [data.created_at for data in result] print('name = ' + str(name)) print('memo = ' + str(memo)) print('created_at = ' + str(created_at)) > name = ['東京', '沖縄'] > memo = ['東京です。', '沖縄です。'] > created_at = [datetime.datetime(2018, 12, 19, 11, 57, 8, 856505), datetime.datetime(2018, 12, 19, 11, 57, 18, 820476)]
result = Location.objects.all()

name = [data.name for data in result]
memo = [data.memo for data in result]
created_at = [data.created_at for data in result]

print('name = ' + str(name))
print('memo = ' + str(memo))
print('created_at = ' + str(created_at))

> name = ['東京', '沖縄']
> memo = ['東京です。', '沖縄です。']
> created_at = [datetime.datetime(2018, 12, 19, 11, 57, 8, 856505), datetime.datetime(2018, 12, 19, 11, 57, 18, 820476)]

参考

Qiita:Django データベース操作 についてのまとめ

https://qiita.com/okoppe8/items/66a8747cf179a538355b

Django公式:QuerySet API reference

https://docs.djangoproject.com/ja/2.1/ref/models/querysets/

Django v1.0 documentation:QuerySet APIリファレンス

http://djangoproject.jp/doc/ja/1.0/ref/models/querysets.html

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です