概要
ジャンゴ(django)のORM(Object-Relational Mapping)を使ってデーターベースにデーターを生成(Create)して、読んで(Read)、更新(Update)して、削除(Delete)する方法(CRUD - Create Read Update Delete)について説明します。
このブログはシリーズです。下記のリンクでシリーズの他の記事を見ることができます。
- ジャンゴ(django)インストール
- ジャンゴ(django)のプロジェクト開始
- ジャンゴ(django)のモデル(models)の使い方
- ジャンゴ(django)の管理者ページ
- ジャンゴ(django)のルーティング(Routing)
- ジャンゴ(django)のORM
- ジャンゴ(django)のビュー(View)
- ジャンゴ(django)のフォーム(Form)
- ジャンゴ(django)プロジェクトをヘロク(Heroku)へアップロードする
また、このブログシリーズで説明したソースコードはgithubに公開されております。下記のリンクで確認できます。
ORMとは?
ORM(Object-Relation Mapping)とは, オブジェクト(Object)と関係型データーベース(Relational)をマッピング(Mapping)することを意味します。簡単に言えばデーターベースのテーブルとオブジェクト(Object)を連結してテーブルにCRUDする時、SQLクエリーを使わなくてもできることです。
私たちは以前のブログ(ジャンゴ(django)のモデル(models)の使い方)ですでにジャンゴ(django)のORM(Object-Relational Mapping)を使う準備をしました。以前のブログで生成したPostモーデル(Models)はデーターベースのblog_postテーブルと連結(Mapping)されています。私たちはこのモーデル(Models)を使ってデーターベースにCRUDをすることでジャンゴ(django)のORM(Object-Relational Mapping)を理解してみようかと思います。
下記のジャンゴ(django)コマンドでジャンゴ(django)が基本的提供してるシェル(Shell)を実行します。
# source venv/bin/activate
# cd django_exercise
python manage.py shell
下記のコードで私たちは以前のブログで作ったPostモデル(Models)を読んできまう。
>>> from blog.models import Post
データー照会(Read)
下記のコードでPostの内容を照会(Read)します。
Post.objects.all()
問題なく実行されたら下記のような結果が見えます。
>>> Post.objects.all()
<QuerySet [<Post: this is a test1 title>, <Post: this is a test2 title>]>
後で使うため、下記のコードでユーザー(User)モデル(Models)を読んできて、データーを照会(Read)して変数に保存します。
>>> from django.contrib.auth.models import User
>>> admin = User.objects.get(username='dev-yakuza')
データー生成(Create)
下記のコードを実行したらPostの新しデーターを生成(Create)してみましょう。
Post.objects.create(author=admin, title='This is a test title from django shell', content='This is a test title from django shell. This is a test title from django shell.')
うまく実行されたら、下記のような結果が見えます。
>>> Post.objects.create(author=admin, title='This is a test title from django shell', content='This is a test title from django shell. This is a test title from django shell.')
<Post: This is a test title from django shell>
データー生成確認
もう一回Postモデル(Models)を照会したら下記のようにデーターが上手く追加されたことが確認できます。
>>> Post.objects.all()
<QuerySet [<Post: this is a test1 title>, <Post: this is a test2 title>, <Post: This is a test title from django shell>]>
新しターミナルで下記のジャンゴ(django)コマンドでテストサーバーを実行した後、管理者ページでデーターを確認したら下記のようにデーターが保存されたことが確認できます。
# source venv/bin/activate
# cd django_exercise
python manage.py runserver

データーベースツールを使って確認しても下記のようにデーターが保存されたことが確認できます。

データー更新(Update)
下記のコードでデーターを照会(Read)して更新(Update)してみましょう。
post = Post.objects.get(title='This is a test title from django shell')
post.title = 'This is a test title updated from django shell'
post.save()
下記のコードで更新した内容を確認することができます。
Post.objects.get(title__contains='updated')
# or
Post.objects.filter(title__contains='updated')
また、以前のブログで作成したPostモデル(Models)のファンクションでも更新できます。
post = Post.objects.get(title__contains='updated')
# post.published_at
post.publish()
# >>> post.published_at
# datetime.datetime(2019, 5, 21, 13, 1, 58, 970677)
データー削除(Delete)
下記のコードえで上で作成したデーターを削除(Delete)してみます。
post = Post.objects.get(title__contains='updated')
post.delete()
# >>> Post.objects.all()
# <QuerySet [<Post: this is a test1 title>, <Post: this is a test2 title>]>
照会条件
今までデーターベースのCRUD(Create Read Update Delete)についてみてみました。下記でデーターを照会(Read)する時使える一般的検索条件について説明します。
- 照会条件
| 照会条件 | 説明 | 使い方 |
|---|---|---|
| __contains | 条件のテキストが含めてるデーターを照会 | Post.objects.filter(title__contains=’test’) |
| __icontains | 条件のテキストの大文字や小文字の区分しなくて含めてるデーターを照会 | Post.objects.filter(title__icontains=’this’) |
| __lt | 小値の場合(lt: less than) | Post.objects.filter(published_at__lt=timezone.now()) |
| __lte | 小値や同じ値の場合(lte: less than or equal) | Post.objects.filter(published_at__lt=timezone.now()) |
| __gt | 大値の場合(gt: greater than) | Post.objects.filter(published_at__gt=timezone.now()) |
| __gte | 大値や同じの場合(gt: greater than or equal) | Post.objects.filter(published_at__gte=timezone.now()) |
| __in | 条件のリストのデーターを照会 | Post.objects.filter(id__in=[1, 2, 3]) |
| __year | 当該年度で照会 | Post.objects.filter(created_at__year=’2019’) |
| __year | 当該月で照会 | Post.objects.filter(created_at__month=’5’) |
| __day | 当該日で照会 | Post.objects.filter(created_at__day=’21’) |
| __isnull | Nullデーター照会 | Post.objects.filter(published_at__isnull=True) |
| __startswith | 条件のテキストで始めるデーターを照会 | Post.objects.filter(title__startswith=’This’) |
| __istartswith | 大文字や小文字を区分しなくて条件のテキストで始めるデーターを照会 | Post.objects.filter(title__istartswith=’this’) |
| __endswith | 条件のテキストで終わるデーターを照会 | Post.objects.filter(title__endswith=’title’) |
| __isendswith | 大文字や小文字を区分しなくて条件のテキストで終わるデーターを照会 | Post.objects.filter(title__isendswith=’title’) |
| __range | 条件の範囲で照会(sqlのbetween) | Post.objects.filter(id__range=(1, 10)) |
- 除外条件(exclude): 下記のように特定条件の除外データーを照会することたできます。
Post.objects.all().exclude(title__contains='This')
- 複数の条件で照会: 下記のように複数の条件でデーターを照会することができます。
Post.objects.filter(title__contains='this', title__endswith='title')
Post.objects.filter(title__contains='this').filter(title__endswith='title')
from django.db.models import Q
Post.objects.filter(Q(title__contains='this') | Q(title__endswith='title'))
Post.objects.filter(Q(title__contains='this') & Q(title__endswith='title'))
- 照会範囲: 下記のように持ってくるデーターの範囲(limit)を指定することができます。
Post.objects.all().exclude(title__contains='This')[:1]
ソーティング
下記のように照会するデーターを昇順と降順でソーティングすることができます。
- 昇順: Post.objects.order_by(‘created_at’)
- 降順: Post.objects.order_by(‘-created_at’)
シェル(Shell)終了
今までジャンゴ(django)のシェル(Shell)を使って簡単にジャンゴ(django)のORM(Object-Relational Mapping)について練習してみました。下記のコードでジャンゴ(django)のシェル(Shell)を終了します。
exit()
完了
これでジャンゴ(django)のORM(Object-Relational Mapping)について見てみました。ORM(Object-Relational Mapping)はジャンゴ(django)以外でもたくさんのフレームワークで使ってる概念なので覚えておくといいと思います。これで私たちはジャンゴ(django)のモデル(Models)を使ってデーターを読んだり生成したり更新したり削除(CRUD - Create Read Update Delete)をすることができます。
私のブログが役に立ちましたか?下にコメントを残してください。それは私にとって大きな大きな力になります!
アプリ広報
Dekuが開発したアプリを使ってみてください。Dekuが開発したアプリはFlutterで開発されています。興味がある方はアプリをダウンロードしてアプリを使ってくれると本当に助かります。






