---
title: "クエリを作成する"
version: 1.11
locale: ja
source: https://docs.djangoproject.com/ja/1.11/topics/db/queries/
canonical: https://djangodocs.dev/ja/1.11/topics/db/queries/
---
# クエリを作成する

一度 [データモデル](/ja/1.11/topics/db/models/) を作成すれば、Django はデータオブジェクトの作成、取得、更新および削除を行えるようにデータベースを抽象化した API を自動的に提供します。本ドキュメントではこの API をどのように用いるかを説明します。多様なモデル探索オプション全てに関する詳細については [データモデルの項目](/ja/1.11/ref/models/) を参照ください。

本項( および参照する文章 )では、以下に定義されたウェブログアプリケーションを構成するモデル定義を利用します:

```python
from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):              # __unicode__ on Python 2
        return self.headline
```

## オブジェクトを作成する

データベースのテーブル上のデータを Python オブジェクトに対応付けるため、 Django は直観的なシステムを利用しています: 1 つのモデルクラスが 1 つのデータベーステーブルに対応し、そのモデルクラスの 1 インスタンスが対応するデータベーステーブルの特定のレコードに対応します。

オブジェクトを生成するためには、作成するモデルのクラスにキーワード引数を渡してインスタンス化し、そのデータをデータベースに保存するために [`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save) を呼び出します。

モデル定義が `mysite/blog/models.py` というファイル内に存在すると仮定すると、利用例は以下のようになります:

```
>>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()
```

この例では内部で `INSERT` SQL 文が処理されます。明示的に [`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save) を呼ぶまで Django はデータベースを操作しません。

[`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save) メソッドは値を返しません。

> **See also**
>
> [`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save) はここには記述されていない多数の高度なオプションを持ちます。詳細については [`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save) の項目を参照してください。
>
> オブジェクトの作成と保存を一つの処理で行うには、 [`create()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.create) メソッドを利用してください。

## オブジェクトに対する変更を保存する

既にデータベース上に存在する 1 つのオブジェクトに対する変更を保存するには、 [`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save) を利用します。

既にデータベースに保存されている `Blog` のインスタンスとして `b5` が与えられたとして、次の例ではその name を変更してデータベースのレコードを更新します:

```
>>> b5.name = 'New name'
>>> b5.save()
```

この例では内部で `UPDATE` SQL 文が処理されます。明示的に [`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save) が呼ばれるまで Django はデータベースを操作しません。

### `ForeignKey` と `ManyToManyField` フィールドを扱う

[`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey) フィールドに対する更新は通常のフィールドに対する更新と完全に同じです -- 単に対象とするフィールドに適した型のオブジェクトを入力するだけです。以下の例では `Entry` のインスタンスである `entry` の `blog` 属性を更新します、 `Entry` および `Blog` のインスタンスは、データベースにすでに保存されているものとします (したがって、以下のように取得できます)。

```
>>> from blog.models import Blog, Entry
>>> entry = Entry.objects.get(pk=1)
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
>>> entry.blog = cheese_blog
>>> entry.save()
```

[`ManyToManyField`](/ja/1.11/ref/models/fields/#django.db.models.ManyToManyField) に対する更新は通常のフィールド更新とは少々異なっています -- リレーションのためレコードを追加するには [`add()`](/ja/1.11/ref/models/relations/#django.db.models.fields.related.RelatedManager.add) メソッドを対象となるフィールドに対して用います。以下の例では entry オブジェクトに Author のインスタンス joe を追加します。

```
>>> from blog.models import Author
>>> joe = Author.objects.create(name="Joe")
>>> entry.authors.add(joe)
```

[`ManyToManyField`](/ja/1.11/ref/models/fields/#django.db.models.ManyToManyField) に対して複数のレコードを一度に追加するには、[`add()`](/ja/1.11/ref/models/relations/#django.db.models.fields.related.RelatedManager.add) 呼び出し時に複数の引数を次の例のように含めます:

```
>>> john = Author.objects.create(name="John")
>>> paul = Author.objects.create(name="Paul")
>>> george = Author.objects.create(name="George")
>>> ringo = Author.objects.create(name="Ringo")
>>> entry.authors.add(john, paul, george, ringo)
```

もし間違った型のオブジェクトを設定もしくは追加しようとすれば Django はエラーを発生させます。

## オブジェクトを取得する

データベースからオブジェクトを取得するには、モデルクラスの [`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) から [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を作ります。

[`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) はデータベース上のオブジェクトの集合を表しています。多数の *フィルター* を持つことができます。フィルターは与えられたパラメータに基づいてクエリの検索結果を絞り込みます。SQL 文においては、 [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) は `SELECT` 句、フィルターは `WHERE` や `LIMIT` のような絞り込みに用いる句に対応しています。

モデルの [`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) を用いることで [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を取得します。各モデルは少なくとも一つの [`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) を持ち、デフォルトでは [`objects`](/ja/1.11/ref/models/class/#django.db.models.Model.objects) という名前を持ちます。以下のようにモデルクラスから直接アクセスしてください。

```
>>> Blog.objects
<django.db.models.manager.Manager object at ...>
>>> b = Blog(name='Foo', tagline='Bar')
>>> b.objects
Traceback:
    ...
AttributeError: "Manager isn't accessible via Blog instances."
```

> **Note**
>
> `Manager` はモデルのインスタンスでなく、モデルのクラスを経由してのみアクセスでき、それは "テーブル水準" の処理と "レコード水準" の処理とで責任を明確に分離するためです。

[`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) はモデルの `QuerySet` の主な取得元になります。たとえば、 `Blog.objects.all()` はデータベース内の `Blog` オブジェクト全てを含んだ [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を返します。

### すべてのオブジェクトを取得する

テーブルからオブジェクトを取得する方法で最も簡単なのは、すべてのオブジェクトを取得することです。それには [`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) に対して [`all()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.all) メソッドを呼びます。

```
>>> all_entries = Entry.objects.all()
```

[`all()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.all) メソッドは、データベース内のすべてのオブジェクトを含んだ [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を返します。

### フィルタを用いて特定のオブジェクトを取得する

[`all()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.all) が返す [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) には、データベーステーブルのすべてのオブジェクトが含まれています。しかし、ふつう必要になるのはオブジェクト全体の集合ではなく、その部分集合でしょう。

そのような部分集合を作るには、条件フィルタを追加して最初の [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を絞り込みます。 [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を絞り込む代表的な方法として次の2つのものがあります。

**`filter(**kwargs)`**

  与えられた検索パラメータにマッチする新しい [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を返します。

**`exclude(**kwargs)`**

  与えられた検索パラメータにマッチ *しない* 新しい [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を返します。

検索パラメータ (上の関数定義における `**kwargs` ) は、以下の [Field lookups](#field-lookups) で説明するフォーマットに従わなければなりません。

たとえば、2006年以降のブログエントリーの [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を取得するには、 [`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) を次のように使用します。

```
Entry.objects.filter(pub_date__year=2006)
```

デフォルトの manager クラスの場合、これは次のコードと等価です。

```
Entry.objects.all().filter(pub_date__year=2006)
```

#### フィルターのチェーン

絞り込みを行った [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) の結果自体も [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) です。そのため、複数の絞り込みをチェーンすることが可能です。たとえば、次のように書くことができます。

```
>>> Entry.objects.filter(
...     headline__startswith='What'
... ).exclude(
...     pub_date__gte=datetime.date.today()
... ).filter(
...     pub_date__gte=datetime.date(2005, 1, 30)
... )
```

これはデータベース内のすべてのエントリーを含む [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) をとり、フィルターを追加し、除外フィルターを追加し、さらにもう1つのフィルターを追加しています。最終的な結果は、"What" で始まるヘッドラインを持ち、2005年1月30日から今日までに公開されたすべてのエントリーを含んだ [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) となります。

#### フィルターを適用した `QuerySet` はユニーク

[`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) に対して絞り込みを適用するごとに、前の [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) から独立した完全に新しい [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) が作られます。絞り込みごとに独立した [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) が作られるため、保存したり何度も再利用したりできます。

実装例:

```
>>> q1 = Entry.objects.filter(headline__startswith="What")
>>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
>>> q3 = q1.filter(pub_date__gte=datetime.date.today())
```

これら3つの `QuerySets` は独立しています。1番目は基本の [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) で、"What" で始まるヘッドラインを持つ全てのエントリーを含みます。2番めは1番目の部分集合で、 `pub_date` が今日または未来の日付であるレコードを除外する追加条件を持ちます。3番目も1番目の部分集合で、 `pub_date` が今日または未来の日付であるレコードだけを選択する追加条件を持ちます。1番目の [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) (`q1`) は、絞り込みの過程において何ら影響を受けません。

#### `QuerySet` は遅延評価される

`QuerySets` は遅延評価されます。 [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を作る行為はいかなるデータベースも引き起こしません。たとえあなたが1日中フィルターのスタックを積み上げたとしても、 [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) が *評価* されるまでは、Django は実際にはクエリを実行しません。次の例を見てください。

```
>>> q = Entry.objects.filter(headline__startswith="What")
>>> q = q.filter(pub_date__lte=datetime.date.today())
>>> q = q.exclude(body_text__icontains="food")
>>> print(q)
```

この例ではデータベースに3回アクセスしているように見えますが、実際にアクセスしているのは、最終行 (`print(q)`) での1回だけです。一般に、 [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) の結果は、明示的に要求するまでデータベースから取得されません。取得するように要求した時点で、 [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) は *評価* され、データベースへのアクセスが発生します。評価が起こる正確なタイミングの詳細については、 [When QuerySets are evaluated](/ja/1.11/ref/models/querysets/#when-querysets-are-evaluated) を参照してください。

### `get()` を用いて1つのオブジェクトを取得する

[`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) は、たとえクエリーにマッチしたのが1つのオブジェクトだけだったとしても、常に [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) を返します。この場合、 [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) には1つの要素だけが含まれることになります。

クエリーにマッチするのは1つのオブジェクトだけだと分かっている場合、  [`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) の [`get()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.get) メソッドを呼べば、そのオブジェクトが直接返されます。

```
>>> one_entry = Entry.objects.get(pk=1)
```

[`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) と同じように、 [`get()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.get) には任意のクエリー表現が使用できます。 繰り返しますが、詳しくはあとで説明する [Field lookups](#field-lookups) を見てください。

[`get()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.get) と [`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) を `[0]` でスライスすることには、次のような違いがあることに注意してください。クエリにマッチする結果が存在しない場合、 [`get()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.get) は `DoesNotExist` 例外を起こします。この例外はクエリーが実行されるモデルクラスの属性です。たとえば上のコードでは、1というプライマリーキーを持つ `Entry` オブジェクトがなければ、Django は `Entry.DoesNotExist` 例外を起こします。

同様に [`get()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.get) のクエリーが2つ以上のアイテムにマッチした場合にも、Djangoは文句を言います。この場合には、やはり同じクエリのモデルクラスの属性の [`MultipleObjectsReturned`](/ja/1.11/ref/exceptions/#django.core.exceptions.MultipleObjectsReturned) 例外が起こります。

### その他の `QuerySet` メソッド

データベースからオブジェクトを検索する必要がある大抵の場合は、 [`all()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.all), [`get()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.get), [`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) および [`exclude()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.exclude) のいずれかを使うことになるでしょう。しかしこれらのメソッドだけでは不十分な場合は、さまざまな [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) メソッドの全リストが掲載されている [QuerySet API Reference](/ja/1.11/ref/models/querysets/#queryset-api) を参照してください。

### `QuerySet` の要素数を制限する

Python のリストスライスのサブセットを使うことで [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) の結果を特定の要素数に制限することができます。これは SQL の `LIMIT` と `OFFSET` 句に対応します。

たとえば、次のコードは最初の5つのオブジェクトを返します (`LIMIT 5`)。

```
>>> Entry.objects.all()[:5]
```

次のコードは、6番目から10番目までのオブジェクトを返します (`OFFSET 5 LIMIT 5`)。

```
>>> Entry.objects.all()[5:10]
```

負のインデックスには対応していません (例: `Entry.objects.all()[-1]`)。

一般に、 [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) をスライスしたとしても、新しい [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) が返り、クエリーの評価は行われません。例外は、Python のリストスライス構文の "step" パラメーターを使用した場合です。たとえば、次のコードは実際にクエリを実行し、最初の10個のオブジェクトから一つおきにとったオブジェクトのリストを返します。

```
>>> Entry.objects.all()[:10:2]
```

リスト (例: `SELECT foo FROM bar LIMIT 1`) ではなく *1つの* オブジェクトを取得するには、スライスではなく単純にリストのインデックスを使用してください。たとえば、次のコードは、ヘッドラインでアルファベット順にソートしたあと、データベースの1番目の `Entry` を返します。

```
>>> Entry.objects.order_by('headline')[0]
```

上の例は次のコードとほとんど同じです。

```
>>> Entry.objects.order_by('headline')[0:1].get()
```

ただし、与えられた条件を満たすオブジェクトが存在しない場合に、前者は `IndexError` を起こすのに対して、後者は `DoesNotExist` を起こすことに注意してください。詳細については [`get()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.get) を参照してください。

### フィールドルックアップ

フィールドルックアップは、SQL の `WHERE` 句の内容を指定する手段です。 [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) メソッド、 [`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) 、 [`exclude()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.exclude) および [`get()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.get) にキーワード引数として指定します。

基本のルックアップキーワード引数は `field__lookuptype=value` という形を取ります (2文字連続するアンダースコアです)。たとえば、

```
>>> Entry.objects.filter(pub_date__lte='2006-01-01')
```

というコードは、(だいたい) 次の SQL 文に変換されます。

```sql
SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
```

> **動作のしくみ**
>
> Python には任意の name-value 形式の引数をとる関数を定義する能力があり、name と value の値を実行時に評価します。詳しい情報については、公式の Python チュートリアルを参照してください。

ルックアップに指定するフィールドはモデルが持つフィールド名でなければなりません。ただし1つだけ例外があり、 [`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey) の場合にはフィールド名の末尾に `_id` を付けた名前を指定することができます。その場合、value  パラメータには外部モデルのプライマリーキーの生の値を書くことが期待されます。

```
>>> Entry.objects.filter(blog_id=4)
```

向こうなキーワード引数を指定すると、ルックアップ関数は `TypeError` を起こします。

データベース API は約30個のルックアップタイプをサポートしており、完全なガイドは [field lookup reference](/ja/1.11/ref/models/querysets/#field-lookups) で見ることができます。ルックアップを使って何ができるのかがよく分かるように、以下によく使う一般的なルックアップをいくつか挙げます。

**[`exact`](/ja/1.11/ref/models/querysets/#std-fieldlookup-exact)**

  完全な ("exact") マッチを行います。たとえば、

  ```
  >>> Entry.objects.get(headline__exact="Cat bites dog")
  ```

  は次のような SQL を生成します。

  ```sql
  SELECT ... WHERE headline = 'Cat bites dog';
  ```

  ルックアップタイプを指定しなかった場合、つまりキーワード引数がダブルアンダースコアを含まない場合、ルックアップタイプは `exact` が指定されたものとみなされます。

  たとえば、次の2つの文は等価です。

  ```
  >>> Blog.objects.get(id__exact=14)  # Explicit form
  >>> Blog.objects.get(id=14)         # __exact is implied
  ```

  `exact` ルックアップが最もよく使われるため、利便性のためにこのようになっています。

**[`iexact`](/ja/1.11/ref/models/querysets/#std-fieldlookup-iexact)**

  case-insensitive  なマッチを行います。したがって、次のクエリ

  ```
  >>> Blog.objects.get(name__iexact="beatles blog")
  ```

  は `"Beatles Blog"` 、 `"beatles blog"` 、あるいは `"BeAtlES blOG"` というタイトルを持つ `Blog` にもマッチします。

**[`contains`](/ja/1.11/ref/models/querysets/#std-fieldlookup-contains)**

  case-sensitive な部分一致テストを行います。たとえば、

  ```
  Entry.objects.get(headline__contains='Lennon')
  ```

  はだいたい次のような SQL に変換されます。

  ```sql
  SELECT ... WHERE headline LIKE '%Lennon%';
  ```

  この例では、ヘッドライン `'Today Lennon honored'` にはマッチしても `'today lennon honored'` にはマッチしないことに注意してください。

  case-insensitive バージョンの [`icontains`](/ja/1.11/ref/models/querysets/#std-fieldlookup-icontains) もあります。

**[`startswith`](/ja/1.11/ref/models/querysets/#std-fieldlookup-startswith) と [`endswith`](/ja/1.11/ref/models/querysets/#std-fieldlookup-endswith)**

  それぞれ starts-with と ends-with 検索を行います。case-insensitive バージョン [`istartswith`](/ja/1.11/ref/models/querysets/#std-fieldlookup-istartswith) と [`iendswith`](/ja/1.11/ref/models/querysets/#std-fieldlookup-iendswith) もあります。

繰り返しになりますが、以上はルックアップの表面をさらったに過ぎません。完全なリファレンスは [field lookup reference](/ja/1.11/ref/models/querysets/#field-lookups) を参照してください。

### リレーションを横断するルックアップ

Django はルックアップの中でリレーションを「横断する」強力で直感的な方法を提供します。あなたのために、背後で SQL の `JOIN` を自動的に実行しています。リレーションを横断するには、使いたいフィールドにたどり着くまで、モデル間を横断する関連フィールドのフィールド名をダブルアンダースコアで繋ぐだけでいいです。

次の例は、`name` に `'Beatles Blog'` を持つ `Blog` のすべての `Entry` オブジェクトを取得します。

```
>>> Entry.objects.filter(blog__name='Beatles Blog')
```

この横断は好きなだけ深くすることができます。

It works backwards, too. To refer to a "reverse" relationship, just use the
lowercase name of the model.

次の例は、 少なくとも1つの `headline` が `'Lennon'` を含む `Entry` を持つ、すべての `Blog` オブジェクトを取得します。

```
>>> Blog.objects.filter(entry__headline__contains='Lennon')
```

If you are filtering across multiple relationships and one of the intermediate
models doesn't have a value that meets the filter condition, Django will treat
it as if there is an empty (all values are `NULL`), but valid, object there.
All this means is that no error will be raised. For example, in this filter:

```
Blog.objects.filter(entry__authors__name='Lennon')
```

(if there was a related `Author` model), if there was no `author`
associated with an entry, it would be treated as if there was also no `name`
attached, rather than raising an error because of the missing `author`.
Usually this is exactly what you want to have happen. The only case where it
might be confusing is if you are using [`isnull`](/ja/1.11/ref/models/querysets/#std-fieldlookup-isnull). Thus:

```
Blog.objects.filter(entry__authors__name__isnull=True)
```

will return `Blog` objects that have an empty `name` on the `author` and
also those which have an empty `author` on the `entry`. If you don't want
those latter objects, you could write:

```
Blog.objects.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)
```

#### 複数の値を持つリレーションの横断

When you are filtering an object based on a
[`ManyToManyField`](/ja/1.11/ref/models/fields/#django.db.models.ManyToManyField) or a reverse
[`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey), there are two different sorts of filter
you may be interested in. Consider the `Blog`/`Entry` relationship
(`Blog` to `Entry` is a one-to-many relation). We might be interested in
finding blogs that have an entry which has both *"Lennon"* in the headline and
was published in 2008. Or we might want to find blogs that have an entry with
*"Lennon"* in the headline as well as an entry that was published
in 2008. Since there are multiple entries associated with a single `Blog`,
both of these queries are possible and make sense in some situations.

The same type of situation arises with a
[`ManyToManyField`](/ja/1.11/ref/models/fields/#django.db.models.ManyToManyField). For example, if an `Entry` has a
[`ManyToManyField`](/ja/1.11/ref/models/fields/#django.db.models.ManyToManyField) called `tags`, we might want to
find entries linked to tags called *"music"* and *"bands"* or we might want an
entry that contains a tag with a name of *"music"* and a status of *"public"*.

To handle both of these situations, Django has a consistent way of processing
[`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) calls. Everything inside a
single [`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) call is applied
simultaneously to filter out items matching all those requirements. Successive
[`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) calls further restrict the set
of objects, but for multi-valued relations, they apply to any object linked to
the primary model, not necessarily those objects that were selected by an
earlier [`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) call.

That may sound a bit confusing, so hopefully an example will clarify. To
select all blogs that contain entries with both *"Lennon"* in the headline
and that were published in 2008 (the same entry satisfying both conditions),
we would write:

```
Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)
```

To select all blogs that contain an entry with *"Lennon"* in the headline
**as well as** an entry that was published in 2008, we would write:

```
Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)
```

Suppose there is only one blog that had both entries containing *"Lennon"* and
entries from 2008, but that none of the entries from 2008 contained *"Lennon"*.
The first query would not return any blogs, but the second query would return
that one blog.

In the second example, the first filter restricts the queryset to all those
blogs linked to entries with *"Lennon"* in the headline. The second filter
restricts the set of blogs *further* to those that are also linked to entries
that were published in 2008. The entries selected by the second filter may or
may not be the same as the entries in the first filter. We are filtering the
`Blog` items with each filter statement, not the `Entry` items.

> **Note**
>
> The behavior of [`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter) for queries
> that span multi-value relationships, as described above, is not implemented
> equivalently for [`exclude()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.exclude). Instead,
> the conditions in a single [`exclude()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.exclude)
> call will not necessarily refer to the same item.
>
> For example, the following query would exclude blogs that contain *both*
> entries with *"Lennon"* in the headline *and* entries published in 2008:
>
> ```
> Blog.objects.exclude(
>     entry__headline__contains='Lennon',
>     entry__pub_date__year=2008,
> )
> ```
>
> However, unlike the behavior when using
> [`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter), this will not limit blogs
> based on entries that satisfy both conditions. In order to do that, i.e.
> to select all blogs that do not contain entries published with *"Lennon"*
> that were published in 2008, you need to make two queries:
>
> ```
> Blog.objects.exclude(
>     entry__in=Entry.objects.filter(
>         headline__contains='Lennon',
>         pub_date__year=2008,
>     ),
> )
> ```

### フィルターはモデルのフィールドを参照できる

これまでに与えられた例では、モデルのフィールドの値を定数と比較するフィルタを作ってきた。しかし、もしモデルのフィールドの値を同じモデルの他のフィールドの値を比較したい時にはどうすればいいのでしょう？

そのような比較を行うために、Django は [`F 式`](/ja/1.11/ref/models/expressions/#django.db.models.F) を用意しています。 `F()` のインスタンスは、クエリの中でモデルのフィールドへの参照として振る舞います。したがって、この参照をクエリの中で使うことで、同じモデルのインスタンスの異なる2つのフィールドの値を比較することができます。

たとえば、pingback の数よりコメントの数が多いすべてのブログエントリーのリストを検索するには、pingback の数を参照する `F()` オブジェクトを作り、その `F()` オブジェクトをクエリの中で次のように使います。

```
>>> from django.db.models import F
>>> Entry.objects.filter(n_comments__gt=F('n_pingbacks'))
```

Django supports the use of addition, subtraction, multiplication,
division, modulo, and power arithmetic with `F()` objects, both with constants
and with other `F()` objects. To find all the blog entries with more than
*twice* as many comments as pingbacks, we modify the query:

```
>>> Entry.objects.filter(n_comments__gt=F('n_pingbacks') * 2)
```

To find all the entries where the rating of the entry is less than the
sum of the pingback count and comment count, we would issue the
query:

```
>>> Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks'))
```

You can also use the double underscore notation to span relationships in
an `F()` object. An `F()` object with a double underscore will introduce
any joins needed to access the related object. For example, to retrieve all
the entries where the author's name is the same as the blog name, we could
issue the query:

```
>>> Entry.objects.filter(authors__name=F('blog__name'))
```

For date and date/time fields, you can add or subtract a
[`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object. The following would return all entries
that were modified more than 3 days after they were published:

```
>>> from datetime import timedelta
>>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))
```

The `F()` objects support bitwise operations by `.bitand()`, `.bitor()`,
`.bitrightshift()`, and `.bitleftshift()`. For example:

```
>>> F('somefield').bitand(16)
```

> **Changed in Django 1.11**
>
> Support for `.bitrightshift()` and `.bitleftshift()` was added.

### `pk` ルックアップショートカット

利便性のために、Django は `pk` ルックアップショートカットを用意しています。pk とは "primary key" を表します。

プライマリーキーが `id` フィールドである `Blog` モデルの例では、次の3つの文はすべて等価です。

```
>>> Blog.objects.get(id__exact=14) # Explicit form
>>> Blog.objects.get(id=14) # __exact is implied
>>> Blog.objects.get(pk=14) # pk implies id__exact
```

The use of `pk` isn't limited to `__exact` queries -- any query term
can be combined with `pk` to perform a query on the primary key of a model:

```
# Get blogs entries with id 1, 4 and 7
>>> Blog.objects.filter(pk__in=[1,4,7])

# Get all blog entries with id > 14
>>> Blog.objects.filter(pk__gt=14)
```

`pk` lookups also work across joins. For example, these three statements are
equivalent:

```
>>> Entry.objects.filter(blog__id__exact=3) # Explicit form
>>> Entry.objects.filter(blog__id=3)        # __exact is implied
>>> Entry.objects.filter(blog__pk=3)        # __pk implies __id__exact
```

### `LIKE` 文の中ではパーセント記号とアンダースコアがエスケープされる

The field lookups that equate to `LIKE` SQL statements (`iexact`,
`contains`, `icontains`, `startswith`, `istartswith`, `endswith`
and `iendswith`) will automatically escape the two special characters used in
`LIKE` statements -- the percent sign and the underscore. (In a `LIKE`
statement, the percent sign signifies a multiple-character wildcard and the
underscore signifies a single-character wildcard.)

This means things should work intuitively, so the abstraction doesn't leak.
For example, to retrieve all the entries that contain a percent sign, just use
the percent sign as any other character:

```
>>> Entry.objects.filter(headline__contains='%')
```

Django takes care of the quoting for you; the resulting SQL will look something
like this:

```sql
SELECT ... WHERE headline LIKE '%\%%';
```

Same goes for underscores. Both percentage signs and underscores are handled
for you transparently.

### キャッシングと `QuerySet`

それぞれの [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) には、データベースへのアクセスを最小にするために内部にキャッシュがあります。キャッシュのしくみを理解すれば、最も効率の良いコードが書けるようになります。

In a newly created [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet), the cache is
empty. The first time a [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) is evaluated
-- and, hence, a database query happens -- Django saves the query results in
the [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet)’s cache and returns the results
that have been explicitly requested (e.g., the next element, if the
[`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) is being iterated over). Subsequent
evaluations of the [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) reuse the cached
results.

Keep this caching behavior in mind, because it may bite you if you don't use
your [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet)s correctly. For example, the
following will create two [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet)s, evaluate
them, and throw them away:

```
>>> print([e.headline for e in Entry.objects.all()])
>>> print([e.pub_date for e in Entry.objects.all()])
```

That means the same database query will be executed twice, effectively doubling
your database load. Also, there's a possibility the two lists may not include
the same database records, because an `Entry` may have been added or deleted
in the split second between the two requests.

To avoid this problem, simply save the
[`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) and reuse it:

```
>>> queryset = Entry.objects.all()
>>> print([p.headline for p in queryset]) # Evaluate the query set.
>>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
```

#### `QuerySet` がキャッシュされない場合

Querysets do not always cache their results.  When evaluating only *part* of
the queryset, the cache is checked, but if it is not populated then the items
returned by the subsequent query are not cached. Specifically, this means that
[limiting the queryset](#limiting-querysets) using an array slice or an
index will not populate the cache.

For example, repeatedly getting a certain index in a queryset object will query
the database each time:

```
>>> queryset = Entry.objects.all()
>>> print(queryset[5]) # Queries the database
>>> print(queryset[5]) # Queries the database again
```

However, if the entire queryset has already been evaluated, the cache will be
checked instead:

```
>>> queryset = Entry.objects.all()
>>> [entry for entry in queryset] # Queries the database
>>> print(queryset[5]) # Uses cache
>>> print(queryset[5]) # Uses cache
```

Here are some examples of other actions that will result in the entire queryset
being evaluated and therefore populate the cache:

```
>>> [entry for entry in queryset]
>>> bool(queryset)
>>> entry in queryset
>>> list(queryset)
```

> **Note**
>
> Simply printing the queryset will not populate the cache. This is because
> the call to `__repr__()` only returns a slice of the entire queryset.

## `Q` オブジェクトを用いた複雑な検索

Keyword argument queries -- in [`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter),
etc. -- are "AND"ed together. If you need to execute more complex queries (for
example, queries with `OR` statements), you can use [`Q objects`](/ja/1.11/ref/models/querysets/#django.db.models.Q).

A [`Q object`](/ja/1.11/ref/models/querysets/#django.db.models.Q) (`django.db.models.Q`) is an object
used to encapsulate a collection of keyword arguments. These keyword arguments
are specified as in "Field lookups" above.

たとえば、次の `Q` オブジェクトは、1つの `LIKE` クエリをカプセル化しています。

```
from django.db.models import Q
Q(question__startswith='What')
```

`Q` オブジェクトは `&` や `|` 演算子を使って結合することができます。2つの `Q` オブジェクトに演算子が作用すると、1つの新しい `Q` オブジェクトが生まれます。

たとえば、次の文は2つの `"question__startswith"` の "OR" を表す、1つの `Q` オブジェクトを生み出します。

```
Q(question__startswith='Who') | Q(question__startswith='What')
```

このコードは次の SQL の `WHERE` 句と同等です。

```
WHERE question LIKE 'Who%' OR question LIKE 'What%'
```

You can compose statements of arbitrary complexity by combining `Q` objects
with the `&` and `|` operators and use parenthetical grouping. Also, `Q`
objects can be negated using the `~` operator, allowing for combined lookups
that combine both a normal query and a negated (`NOT`) query:

```
Q(question__startswith='Who') | ~Q(pub_date__year=2005)
```

Each lookup function that takes keyword-arguments
(e.g. [`filter()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.filter),
[`exclude()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.exclude),
[`get()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.get)) can also be passed one or more
`Q` objects as positional (not-named) arguments. If you provide multiple
`Q` object arguments to a lookup function, the arguments will be "AND"ed
together. For example:

```
Poll.objects.get(
    Q(question__startswith='Who'),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
```

... roughly translates into the SQL:

```
SELECT * from polls WHERE question LIKE 'Who%'
    AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
```

Lookup functions can mix the use of `Q` objects and keyword arguments. All
arguments provided to a lookup function (be they keyword arguments or `Q`
objects) are "AND"ed together. However, if a `Q` object is provided, it must
precede the definition of any keyword arguments. For example:

```
Poll.objects.get(
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
    question__startswith='Who',
)
```

... would be a valid query, equivalent to the previous example; but:

```
# INVALID QUERY
Poll.objects.get(
    question__startswith='Who',
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
```

... would not be valid.

> **See also**
>
> The [OR lookups examples](https://github.com/django/django/blob/master/tests/or_lookups/tests.py) in the Django unit tests show some possible uses
> of `Q`.

## オブジェクトを比較する

To compare two model instances, just use the standard Python comparison operator,
the double equals sign: `==`. Behind the scenes, that compares the primary
key values of two models.

Using the `Entry` example above, the following two statements are equivalent:

```
>>> some_entry == other_entry
>>> some_entry.id == other_entry.id
```

If a model's primary key isn't called `id`, no problem. Comparisons will
always use the primary key, whatever it's called. For example, if a model's
primary key field is called `name`, these two statements are equivalent:

```
>>> some_obj == other_obj
>>> some_obj.name == other_obj.name
```

## オブジェクトを削除する

The delete method, conveniently, is named
[`delete()`](/ja/1.11/ref/models/instances/#django.db.models.Model.delete). This method immediately deletes the
object and returns the number of objects deleted and a dictionary with
the number of deletions per object type. Example:

```
>>> e.delete()
(1, {'weblog.Entry': 1})
```

You can also delete objects in bulk. Every
[`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) has a
[`delete()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.delete) method, which deletes all
members of that [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet).

For example, this deletes all `Entry` objects with a `pub_date` year of
2005:

```
>>> Entry.objects.filter(pub_date__year=2005).delete()
(5, {'webapp.Entry': 5})
```

Keep in mind that this will, whenever possible, be executed purely in SQL, and
so the `delete()` methods of individual object instances will not necessarily
be called during the process. If you've provided a custom `delete()` method
on a model class and want to ensure that it is called, you will need to
"manually" delete instances of that model (e.g., by iterating over a
[`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) and calling `delete()` on each
object individually) rather than using the bulk
[`delete()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.delete) method of a
[`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet).

When Django deletes an object, by default it emulates the behavior of the SQL
constraint `ON DELETE CASCADE` -- in other words, any objects which had
foreign keys pointing at the object to be deleted will be deleted along with
it. For example:

```
b = Blog.objects.get(pk=1)
# This will delete the Blog and all of its Entry objects.
b.delete()
```

This cascade behavior is customizable via the
[`on_delete`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey.on_delete) argument to the
[`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey).

Note that [`delete()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.delete) is the only
[`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) method that is not exposed on a
[`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) itself. This is a safety mechanism to
prevent you from accidentally requesting `Entry.objects.delete()`, and
deleting *all* the entries. If you *do* want to delete all the objects, then
you have to explicitly request a complete query set:

```
Entry.objects.all().delete()
```

## モデルのインスタンスをコピーする

Although there is no built-in method for copying model instances, it is
possible to easily create new instance with all fields' values copied. In the
simplest case, you can just set `pk` to `None`. Using our blog example:

```
blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1

blog.pk = None
blog.save() # blog.pk == 2
```

Things get more complicated if you use inheritance. Consider a subclass of
`Blog`:

```
class ThemeBlog(Blog):
    theme = models.CharField(max_length=200)

django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme='python')
django_blog.save() # django_blog.pk == 3
```

Due to how inheritance works, you have to set both `pk` and `id` to None:

```
django_blog.pk = None
django_blog.id = None
django_blog.save() # django_blog.pk == 4
```

This process doesn't copy relations that aren't part of the model's database
table. For example, `Entry` has a `ManyToManyField` to `Author`. After
duplicating an entry, you must set the many-to-many relations for the new
entry:

```
entry = Entry.objects.all()[0] # some previous entry
old_authors = entry.authors.all()
entry.pk = None
entry.save()
entry.authors.set(old_authors)
```

For a `OneToOneField`, you must duplicate the related object and assign it
to the new object's field to avoid violating the one-to-one unique constraint.
For example, assuming `entry` is already duplicated as above:

```
detail = EntryDetail.objects.all()[0]
detail.pk = None
detail.entry = entry
detail.save()
```

## 複数のオブジェクトを一括で更新する

Sometimes you want to set a field to a particular value for all the objects in
a [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet). You can do this with the
[`update()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.update) method. For example:

```
# Update all the headlines with pub_date in 2007.
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
```

You can only set non-relation fields and [`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey)
fields using this method. To update a non-relation field, provide the new value
as a constant. To update [`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey) fields, set the
new value to be the new model instance you want to point to. For example:

```
>>> b = Blog.objects.get(pk=1)

# Change every Entry so that it belongs to this Blog.
>>> Entry.objects.all().update(blog=b)
```

The `update()` method is applied instantly and returns the number of rows
matched by the query (which may not be equal to the number of rows updated if
some rows already have the new value). The only restriction on the
[`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) being updated is that it can only
access one database table: the model's main table. You can filter based on
related fields, but you can only update columns in the model's main
table. Example:

```
>>> b = Blog.objects.get(pk=1)

# Update all the headlines belonging to this Blog.
>>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')
```

Be aware that the `update()` method is converted directly to an SQL
statement. It is a bulk operation for direct updates. It doesn't run any
[`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save) methods on your models, or emit the
`pre_save` or `post_save` signals (which are a consequence of calling
[`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save)), or honor the
[`auto_now`](/ja/1.11/ref/models/fields/#django.db.models.DateField.auto_now) field option.
If you want to save every item in a [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet)
and make sure that the [`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save) method is called on
each instance, you don't need any special function to handle that. Just loop
over them and call [`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save):

```
for item in my_queryset:
    item.save()
```

Calls to update can also use [`F expressions`](/ja/1.11/ref/models/expressions/#django.db.models.F) to
update one field based on the value of another field in the model. This is
especially useful for incrementing counters based upon their current value. For
example, to increment the pingback count for every entry in the blog:

```
>>> Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
```

However, unlike `F()` objects in filter and exclude clauses, you can't
introduce joins when you use `F()` objects in an update -- you can only
reference fields local to the model being updated. If you attempt to introduce
a join with an `F()` object, a `FieldError` will be raised:

```
# This will raise a FieldError
>>> Entry.objects.update(headline=F('blog__name'))
```

## Related objects

When you define a relationship in a model (i.e., a
[`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey),
[`OneToOneField`](/ja/1.11/ref/models/fields/#django.db.models.OneToOneField), or
[`ManyToManyField`](/ja/1.11/ref/models/fields/#django.db.models.ManyToManyField)), instances of that model will have
a convenient API to access the related object(s).

Using the models at the top of this page, for example, an `Entry` object `e`
can get its associated `Blog` object by accessing the `blog` attribute:
`e.blog`.

(Behind the scenes, this functionality is implemented by Python [descriptors](https://docs.python.org/3/howto/descriptor.html).
This shouldn't really matter to you, but we point it out here for the curious.)

Django also creates API accessors for the "other" side of the relationship --
the link from the related model to the model that defines the relationship.
For example, a `Blog` object `b` has access to a list of all related
`Entry` objects via the `entry_set` attribute: `b.entry_set.all()`.

All examples in this section use the sample `Blog`, `Author` and `Entry`
models defined at the top of this page.

### One-to-many relationships

#### Forward

If a model has a [`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey), instances of that model
will have access to the related (foreign) object via a simple attribute of the
model.

実装例:

```
>>> e = Entry.objects.get(id=2)
>>> e.blog # Returns the related Blog object.
```

You can get and set via a foreign-key attribute. As you may expect, changes to
the foreign key aren't saved to the database until you call
[`save()`](/ja/1.11/ref/models/instances/#django.db.models.Model.save). Example:

```
>>> e = Entry.objects.get(id=2)
>>> e.blog = some_blog
>>> e.save()
```

If a [`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey) field has `null=True` set (i.e.,
it allows `NULL` values), you can assign `None` to remove the relation.
Example:

```
>>> e = Entry.objects.get(id=2)
>>> e.blog = None
>>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
```

Forward access to one-to-many relationships is cached the first time the
related object is accessed. Subsequent accesses to the foreign key on the same
object instance are cached. Example:

```
>>> e = Entry.objects.get(id=2)
>>> print(e.blog)  # Hits the database to retrieve the associated Blog.
>>> print(e.blog)  # Doesn't hit the database; uses cached version.
```

Note that the [`select_related()`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet.select_related)
[`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) method recursively prepopulates the
cache of all one-to-many relationships ahead of time. Example:

```
>>> e = Entry.objects.select_related().get(id=2)
>>> print(e.blog)  # Doesn't hit the database; uses cached version.
>>> print(e.blog)  # Doesn't hit the database; uses cached version.
```

#### Following relationships "backward"

If a model has a [`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey), instances of the
foreign-key model will have access to a [`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) that
returns all instances of the first model. By default, this
[`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) is named `FOO_set`, where `FOO` is the
source model name, lowercased. This [`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) returns
`QuerySets`, which can be filtered and manipulated as described in the
"Retrieving objects" section above.

実装例:

```
>>> b = Blog.objects.get(id=1)
>>> b.entry_set.all() # Returns all Entry objects related to Blog.

# b.entry_set is a Manager that returns QuerySets.
>>> b.entry_set.filter(headline__contains='Lennon')
>>> b.entry_set.count()
```

You can override the `FOO_set` name by setting the
[`related_name`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey.related_name) parameter in the
[`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey) definition. For example, if the `Entry`
model was altered to `blog = ForeignKey(Blog, on_delete=models.CASCADE,
related_name='entries')`, the above example code would look like this:

```
>>> b = Blog.objects.get(id=1)
>>> b.entries.all() # Returns all Entry objects related to Blog.

# b.entries is a Manager that returns QuerySets.
>>> b.entries.filter(headline__contains='Lennon')
>>> b.entries.count()
```

#### Using a custom reverse manager

By default the [`RelatedManager`](/ja/1.11/ref/models/relations/#django.db.models.fields.related.RelatedManager) used
for reverse relations is a subclass of the [default manager](/ja/1.11/topics/db/managers/#manager-names)
for that model. If you would like to specify a different manager for a given
query you can use the following syntax:

```
from django.db import models

class Entry(models.Model):
    #...
    objects = models.Manager()  # Default Manager
    entries = EntryManager()    # Custom Manager

b = Blog.objects.get(id=1)
b.entry_set(manager='entries').all()
```

If `EntryManager` performed default filtering in its `get_queryset()`
method, that filtering would apply to the `all()` call.

Of course, specifying a custom reverse manager also enables you to call its
custom methods:

```
b.entry_set(manager='entries').is_published()
```

#### Additional methods to handle related objects

In addition to the [`QuerySet`](/ja/1.11/ref/models/querysets/#django.db.models.query.QuerySet) methods defined in
"Retrieving objects" above, the [`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey)
[`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) has additional methods used to handle the
set of related objects. A synopsis of each is below, and complete details can
be found in the [related objects reference](/ja/1.11/ref/models/relations/).

**`add(obj1, obj2, ...)`**

  Adds the specified model objects to the related object set.

**`create(**kwargs)`**

  Creates a new object, saves it and puts it in the related object set.
  Returns the newly created object.

**`remove(obj1, obj2, ...)`**

  Removes the specified model objects from the related object set.

**`clear()`**

  Removes all objects from the related object set.

**`set(objs)`**

  Replace the set of related objects.

To assign the members of a related set, use the `set()` method with an
iterable of object instances or a list of primary key values. For example:

```
b = Blog.objects.get(id=1)
b.entry_set.set([e1, e2])
```

In this example, `e1` and `e2` can be full Entry instances, or integer
primary key values.

If the `clear()` method is available, any pre-existing objects will be
removed from the `entry_set` before all objects in the iterable (in this
case, a list) are added to the set. If the `clear()` method is *not*
available, all objects in the iterable will be added without removing any
existing elements.

Each "reverse" operation described in this section has an immediate effect on
the database. Every addition, creation and deletion is immediately and
automatically saved to the database.

### Many-to-many relationships

Both ends of a many-to-many relationship get automatic API access to the other
end. The API works just as a "backward" one-to-many relationship, above.

The only difference is in the attribute naming: The model that defines the
[`ManyToManyField`](/ja/1.11/ref/models/fields/#django.db.models.ManyToManyField) uses the attribute name of that
field itself, whereas the "reverse" model uses the lowercased model name of the
original model, plus `'_set'` (just like reverse one-to-many relationships).

An example makes this easier to understand:

```
e = Entry.objects.get(id=3)
e.authors.all() # Returns all Author objects for this Entry.
e.authors.count()
e.authors.filter(name__contains='John')

a = Author.objects.get(id=5)
a.entry_set.all() # Returns all Entry objects for this Author.
```

Like [`ForeignKey`](/ja/1.11/ref/models/fields/#django.db.models.ForeignKey),
[`ManyToManyField`](/ja/1.11/ref/models/fields/#django.db.models.ManyToManyField) can specify
[`related_name`](/ja/1.11/ref/models/fields/#django.db.models.ManyToManyField.related_name). In the above example,
if the [`ManyToManyField`](/ja/1.11/ref/models/fields/#django.db.models.ManyToManyField) in `Entry` had specified
`related_name='entries'`, then each `Author` instance would have an
`entries` attribute instead of `entry_set`.

### One-to-one relationships

One-to-one relationships are very similar to many-to-one relationships. If you
define a [`OneToOneField`](/ja/1.11/ref/models/fields/#django.db.models.OneToOneField) on your model, instances of
that model will have access to the related object via a simple attribute of the
model.

For example:

```
class EntryDetail(models.Model):
    entry = models.OneToOneField(Entry, on_delete=models.CASCADE)
    details = models.TextField()

ed = EntryDetail.objects.get(id=2)
ed.entry # Returns the related Entry object.
```

The difference comes in "reverse" queries. The related model in a one-to-one
relationship also has access to a [`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) object, but
that [`Manager`](/ja/1.11/topics/db/managers/#django.db.models.Manager) represents a single object, rather than
a collection of objects:

```
e = Entry.objects.get(id=2)
e.entrydetail # returns the related EntryDetail object
```

If no object has been assigned to this relationship, Django will raise
a `DoesNotExist` exception.

Instances can be assigned to the reverse relationship in the same way as
you would assign the forward relationship:

```
e.entrydetail = ed
```

### How are the backward relationships possible?

Other object-relational mappers require you to define relationships on both
sides. The Django developers believe this is a violation of the DRY (Don't
Repeat Yourself) principle, so Django only requires you to define the
relationship on one end.

But how is this possible, given that a model class doesn't know which other
model classes are related to it until those other model classes are loaded?

The answer lies in the [`app registry`](/ja/1.11/ref/applications/#django.apps.apps). When Django
starts, it imports each application listed in [`INSTALLED_APPS`](/ja/1.11/ref/settings/#std-setting-INSTALLED_APPS), and
then the `models` module inside each application. Whenever a new model class
is created, Django adds backward-relationships to any related models. If the
related models haven't been imported yet, Django keeps tracks of the
relationships and adds them when the related models eventually are imported.

For this reason, it's particularly important that all the models you're using
be defined in applications listed in [`INSTALLED_APPS`](/ja/1.11/ref/settings/#std-setting-INSTALLED_APPS). Otherwise,
backwards relations may not work properly.

### Queries over related objects

Queries involving related objects follow the same rules as queries involving
normal value fields. When specifying the value for a query to match, you may
use either an object instance itself, or the primary key value for the object.

For example, if you have a Blog object `b` with `id=5`, the following
three queries would be identical:

```
Entry.objects.filter(blog=b) # Query using object instance
Entry.objects.filter(blog=b.id) # Query using id from instance
Entry.objects.filter(blog=5) # Query using id directly
```

## 生の SQLへのフォールバック

If you find yourself needing to write an SQL query that is too complex for
Django's database-mapper to handle, you can fall back on writing SQL by hand.
Django has a couple of options for writing raw SQL queries; see
[素の SQL 文の実行](/ja/1.11/topics/db/sql/).

Finally, it's important to note that the Django database layer is merely an
interface to your database. You can access your database via other tools,
programming languages or database frameworks; there's nothing Django-specific
about your database.
