Web制作、Web開発の歩き方

初心者のためのDjango入門

■第8話:ORM(Object-Relational Mapping)の威力

(最終更新日:2023.07.18)

Djangoフレームワークのイメージ
この記事は5分で読めます!
(絵が小さい場合はスマホを横に)

「ORMって何が良いの?」

Webアプリケーションフレームワークを使い始めたばかりの頃は、ORMの利点がすぐに理解できない人も多いだろう。 実際、新しいルールを本当の意味で理解するには時間がかかる。直接データベースにアクセスできる生SQLを使う方が良いと感じることもあるだろう。 そんな方に向けて、今回はDjangoのORMを例に、ORMの魅力について説明したいと思う。


1ORMのメリット

ORMを使う利点は、主に3点ある。

①SQL文を書くことなく、使用しているプログラミング言語(Python)だけでデータベースの操作ができる。
②非常に簡潔な命令で操作できる。
③Modelと連携するため、Modelやmigrationファイルにtableの型定義やキー制約などの記録が残せる。

①および②に関して、ORMを用いると、定型的なCRUD操作は非常に簡単に実行できることが分かるだろう。 指定したModelのClass(以下のClass1)に対して命令するだけである。 Updateの場合はデータを指定し、変更内容を挿入して、保存するという3段階のプロセスが必要だが、 それでもPython上で関数やライブラリを使ってSQLを操作するよりはるかに簡単である。 言葉で説明するよりも、以下のコードを見ていただく方が理解しやすいだろう。 短いコードで簡単に書けるというのは、ルールを知っている人なら、誰がやっても書きやすく、誰が見ても分かりやすいことを意味する。 チームでコーディングする際、このことは非常に重要になるので覚えておこう。

DjangoのORMによるCRUD操作

ちなみに、以下はORMを使用しない場合の操作で、上述のReadと同じ操作を行っている。 全件データを取得したいだけなのに、かなり手間がかかることが分かる。 さらに、Whereのような条件を指定する場合、SQLインジェクション対策のためにプレースホルダーを書く必要がある。 より長い命令になるということだ。 データベースの設定からセキュリティ対策まで、ORMは面倒な処理をすべて裏で行ってくれる。 これはかなり便利な機能で、その恩恵を受けて、ユーザーは簡潔に安全にコードを書くことができる。

MySQLdbを使ったデータベース操作

③に関しては、以前書いたDjangoのModelに関する記事を見てほしい。 DjangoではModel作成からデータを取得するところまで、一貫して操作することができる。 履歴が残るので、どんなTable設計をしたかがDjangoのコードを見るだけで分かるだろう。


2.ORMの威力

ORMの強みは、特にデータ取得の際に発揮される。 データ取得方法として「objects.all」のほかに「objects.get」と「objects.filter」が利用できる。 「objects.get」は、取得データが1つの場合に使用する。それ以外の場合は「objects.filter」を用いる。 このような簡単な命令で、目的のデータを取得できる。

また、これらの返り値の違いを説明しておこう。 「objects.get」ではオブジェクトそのものを取得し、「objects.filter」ではQuerySetを取得している。 そのため、filterの場合はfor文で展開して値を取得する必要がある。 しかし、どちらの方法でも、簡単な命令でデータを取得できる。大きな利点である。 また、firstやlastといった、最初や最後のデータのみを取得する便利な命令も用意されている。ぜひそちらも試してみよう。

DjangoのORM、getとfilterによるデータ取得

さらに、Djangoの機能としてForeign Keyの指定が非常に便利である。 通常、入力に関する選択肢は対象のTableデータから参照する必要があるが、DjangoではForeign Keyを指定するだけで、その処理を自動で行ってくれる。 加えて、親Tableデータ(この場合はSubject)が削除された場合、CASCADEを有効にしていれば、関連するデータも自動で削除される。 これにより、データを管理する手間が大幅に軽減される。

DjangoのForeign Key設定、選択肢をSubjectテーブルから取得してくれる

3.素のSQLを使いたいときは

これまで説明した命令は、ORMで実行できる。もちろん、1対1、1対多、多対多のリレーションなどにも対応できる。 しかし、複雑な命令や参照(検索)のパフォーマンスが必要な場合は、素のSQLで操作することが求められることもある。

Djangoでは、そのような場合にobjects.rawという命令を利用できる。 SQLを書く部分はrawの括弧内だけに限定されるため、冗長な記述を避けられ、命令の実行が可能になる。 ただし、Where句などで検索条件を指定する場合は、プレースホルダーを用いた書き方が必要である。

Djangoで素のSQLを使う操作

DjangoのORMは保守性からセキュリティ対策まで考慮されており、ORMで実現可能な命令は、極力ORMを利用することが推奨される。


4.まとめ

今回、ORMの威力について説明した。ORMが活躍するのはDjangoだけでなく、他のWebアプリケーションフレームワークでも同様である。 今回の説明で、素のSQLで実装する場合と比べ、どれだけ簡単に、安全にコードを書けるかを感じていただければ幸いである。


▼参考図書、サイト

Django パーフェクトマスター  Udemy(小野宏司)
DjangoのModel.objects.filterの使い方【QuerySet】  ユーニックス総合研究所 | なるぽのブログ


Django for Absolute Beginners ■ Episode 8: The Power of ORM (Object-Relational Mapping) (Last updated: 2023.07.18) Image of Django framework This article takes about 5 minutes to read! (Rotate your phone for a larger image) “What’s so great about ORM?” When you’re just starting out with web frameworks, it’s often hard to immediately grasp the benefits of ORM. You might feel more comfortable using raw SQL to directly access the database. This article explains the advantages of ORM using Django as an example. [Contents] Benefits of ORM Power of ORM When You Want Raw SQL Summary 1. Benefits of ORM There are three main benefits to using ORM: ① You can manipulate the database using only Python, without writing SQL. ② You can perform operations with very concise commands. ③ Since ORM works with Models, your table definitions and constraints are tracked in the code via models and migration files. For ① and ②, ORM allows you to perform standard CRUD operations with minimal code by interacting with the defined model class. Updating data involves three steps: select the data, make changes, and save—but it’s still much simpler than writing SQL with libraries. This simplicity makes the code easier to write and read for any team member, which is essential for collaborative development. CRUD Operations Using Django ORM Here’s a comparison using raw SQL to do the same "Read" operation. You can see how much more code is involved, even just to retrieve all records. If you need conditions like WHERE clauses, you also have to consider SQL injection and use placeholders. ORM handles these tedious details behind the scenes, making your code both safer and simpler. Database Access Using MySQLdb As for ③, refer to our previous article on Django models. With Django, you can manage everything from model creation to data retrieval in a unified way. This leaves a traceable record of your table structure in the code. 2. The Power of ORM ORM really shines when retrieving data. In Django, you can use `objects.all`, `objects.get`, and `objects.filter` to query data. Use `get` when you expect exactly one result, and `filter` when you expect multiple results. The return values differ: `get` returns a single object, while `filter` returns a QuerySet, so you’ll need a `for` loop to iterate through it. Both are extremely simple to use and improve readability. You can also use handy functions like `first()` and `last()` to fetch only the first or last record. Data Retrieval with get() and filter() in Django ORM Django’s support for Foreign Keys is another powerful feature. Instead of manually linking input options from a related table, Django handles this automatically when a Foreign Key is specified. And if the parent table (e.g., Subject) is deleted, related data will also be removed automatically if you use CASCADE. This simplifies data management significantly. Foreign Key in Django - Automatically Fetching Options from Subject Table 3. When You Want to Use Raw SQL The commands introduced so far can all be executed with ORM. Django supports various relationship types such as one-to-one, one-to-many, and many-to-many. However, for complex queries or performance-critical operations, raw SQL may still be necessary. In such cases, Django allows you to use `objects.raw`. The raw SQL is confined to just the string inside the `raw()` call, avoiding unnecessary clutter. Be sure to use placeholders to prevent SQL injection when using WHERE clauses. Using Raw SQL in Django Django’s ORM is designed with maintainability and security in mind. Whenever possible, use ORM commands instead of raw SQL. 4. Summary This article explored the strengths of ORM. Django is not the only framework that benefits from ORM—many modern web frameworks provide similar advantages. Hopefully, you now see how ORM simplifies and secures your code compared to using raw SQL. ▼ References   Django Perfect Master - Udemy (Koji Ono)   How to Use Django Model.objects.filter [QuerySet] - Unix Research Institute | Narupo Blog