クエリを作成するLink to this heading

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

Throughout this guide (and in the reference), we'll refer to the following models, which comprise a blog application:

Python
from datetime import date

from django.db import models


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

    def __str__(self):
        return self.name


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

    def __str__(self):
        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(default=date.today)
    authors = models.ManyToManyField(Author)
    number_of_comments = models.IntegerField(default=0)
    number_of_pingbacks = models.IntegerField(default=0)
    rating = models.IntegerField(default=5)

    def __str__(self):
        return self.headline

オブジェクトを作成するLink to this heading

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

オブジェクトを生成するためには、作成するモデルのクラスにキーワード引数を渡してインスタンス化し、そのデータをデータベースに保存するために save() を呼び出します。

Assuming models live in a file mysite/blog/models.py, here's an example:

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

この例では内部で INSERT SQL 文が処理されます。明示的に save() を呼ぶまで Django はデータベースを操作しません。

save() メソッドは値を返しません。

オブジェクトに対する変更を保存するLink to this heading

既にデータベース上に存在する 1 つのオブジェクトに対する変更を保存するには、 save() を利用します。

Given a Blog instance b5 that has already been saved to the database, this example changes its name and updates its record in the database:

Python console
>>> b5.name = "New name"
>>> b5.save()

この例では内部で UPDATE SQL 文が処理されます。明示的に save() が呼ばれるまで Django はデータベースを操作しません。

ForeignKeyManyToManyField フィールドを扱うLink to this heading

Updating a ForeignKey field works exactly the same way as saving a normal field -- assign an object of the right type to the field in question. This example updates the blog attribute of an Entry instance entry, assuming appropriate instances of Entry and Blog are already saved to the database (so we can retrieve them below):

Python console
>>> 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()

Updating a ManyToManyField works a little differently -- use the add() method on the field to add a record to the relation. This example adds the Author instance joe to the entry object:

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

To add multiple records to a ManyToManyField in one go, include multiple arguments in the call to add(), like this:

Python console
>>> 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 はエラーを発生させます。

オブジェクトを取得するLink to this heading

データベースからオブジェクトを取得するには、モデルクラスの Manager から QuerySet を作ります。

QuerySet はデータベース上のオブジェクトの集合を表しています。多数の フィルター を持つことができます。フィルターは与えられたパラメータに基づいてクエリの検索結果を絞り込みます。SQL 文においては、 QuerySetSELECT 句、フィルターは WHERELIMIT のような絞り込みに用いる句に対応しています。

You get a QuerySet by using your model's Manager. Each model has at least one Manager, and it's called objects by default. Access it directly via the model class, like so:

Python console
>>> 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."

Manager はモデルの QuerySet の主な取得元になります。たとえば、 Blog.objects.all() はデータベース内の Blog オブジェクト全てを含んだ QuerySet を返します。

すべてのオブジェクトを取得するLink to this heading

The simplest way to retrieve objects from a table is to get all of them. To do this, use the all() method on a Manager:

Python console
>>> all_entries = Entry.objects.all()

all() メソッドは、データベース内のすべてのオブジェクトを含んだ QuerySet を返します。

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

all() が返す QuerySet には、データベーステーブルのすべてのオブジェクトが含まれています。しかし、ふつう必要になるのはオブジェクト全体の集合ではなく、その部分集合でしょう。

そのような部分集合を作るには、条件フィルタを追加して最初の QuerySet を絞り込みます。 QuerySet を絞り込む代表的な方法として次の2つのものがあります。

filter(**kwargs)

与えられた検索パラメータにマッチする新しい QuerySet を返します。

exclude(**kwargs)

与えられた検索パラメータにマッチ しない 新しい QuerySet を返します。

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

たとえば、2006年以降のブログエントリーの QuerySet を取得するには、 filter() を次のように使用します。

Code
Entry.objects.filter(pub_date__year=2006)

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

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

フィルターのチェーンLink to this heading

The result of refining a QuerySet is itself a QuerySet, so it's possible to chain refinements together. For example:

Python console
>>> Entry.objects.filter(headline__startswith="What").exclude(
...     pub_date__gte=datetime.date.today()
... ).filter(pub_date__gte=datetime.date(2005, 1, 30))

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

フィルターを適用した QuerySet はユニークLink to this heading

QuerySet に対して絞り込みを適用するごとに、前の QuerySet から独立した完全に新しい QuerySet が作られます。絞り込みごとに独立した QuerySet が作られるため、保存したり何度も再利用したりできます。

Example:

Python console
>>> 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 で、"What" で始まるヘッドラインを持つ全てのエントリーを含みます。2番めは1番目の部分集合で、 pub_date が今日または未来の日付であるレコードを除外する追加条件を持ちます。3番目も1番目の部分集合で、 pub_date が今日または未来の日付であるレコードだけを選択する追加条件を持ちます。1番目の QuerySet (q1) は、絞り込みの過程において何ら影響を受けません。

QuerySet は遅延評価されるLink to this heading

QuerySets は遅延評価されます。 QuerySet を作る行為はいかなるデータベース操作も引き起こしません。たとえあなたが 1 日中フィルターのスタックを積み上げたとしても、QuerySet評価される までは、Django は実際にはクエリを実行しません。次の例を見てください。

Python console
>>> 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 の結果は、明示的に要求するまでデータベースから取得されません。取得するように要求した時点で、 QuerySet評価 され、データベースへのアクセスが発生します。評価が起こる正確なタイミングの詳細については、 QuerySet が評価されるタイミング を参照してください。

get() を用いて1つのオブジェクトを取得するLink to this heading

filter() は、たとえクエリーにマッチしたのが1つのオブジェクトだけだったとしても、常に QuerySet を返します。この場合、 QuerySet には1つの要素だけが含まれることになります。

クエリーにマッチするのは1つのオブジェクトだけだと分かっている場合、 Managerget() メソッドを呼べば、そのオブジェクトが直接返されます。

Python console
>>> one_entry = Entry.objects.get(pk=1)

filter() と同じように、 get() には任意のクエリー表現が使用できます。 繰り返しますが、詳しくはあとで説明する Field lookups を見てください。

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

同様に get() のクエリーが2つ以上のアイテムにマッチした場合にも、Djangoは文句を言います。この場合には、やはり同じクエリのモデルクラスの属性の MultipleObjectsReturned 例外が起こります。

その他の QuerySet メソッドLink to this heading

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

QuerySet の要素数を制限するLink to this heading

Python のリストスライスのサブセットを使うことで QuerySet の結果を特定の要素数に制限することができます。これは SQL の LIMITOFFSET 句に対応します。

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

Python console
>>> Entry.objects.all()[:5]

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

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

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

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

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

Further filtering or ordering of a sliced queryset is prohibited due to the ambiguous nature of how that might work.

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

Python console
>>> Entry.objects.order_by("headline")[0]

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

Python console
>>> Entry.objects.order_by("headline")[0:1].get()

ただし、与えられた条件を満たすオブジェクトが存在しない場合に、前者は IndexError を起こすのに対して、後者は DoesNotExist を起こすことに注意してください。詳細については get() を参照してください。

フィールドルックアップLink to this heading

フィールドルックアップは、SQL の WHERE 句の内容を指定する手段です。 QuerySet メソッド、 filter()exclude() および get() にキーワード引数として指定します。

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

Python console
>>> Entry.objects.filter(pub_date__lte="2006-01-01")

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

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

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

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

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

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

exact

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

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

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

SQL
SELECT ... WHERE headline = 'Cat bites dog';

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

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

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

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

iexact

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

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

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

contains

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

Code
Entry.objects.get(headline__contains="Lennon")

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

SQL
SELECT ... WHERE headline LIKE '%Lennon%';

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

case-insensitive バージョンの icontains もあります。

startswithendswith

それぞれ starts-with と ends-with 検索を行います。case-insensitive バージョン istartswithiendswith もあります。

繰り返しになりますが、以上はルックアップの表面をさらったに過ぎません。完全なリファレンスは field lookup reference を参照してください。

リレーションを横断するルックアップLink to this heading

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

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

Python console
>>> Entry.objects.filter(blog__name="Beatles Blog")

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

It works backwards, too. While it can be customized, by default you refer to a "reverse" relationship in a lookup using the lowercase name of the model.

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

Python console
>>> Blog.objects.filter(entry__headline__contains="Lennon")

複数のリレーションにまたがってフィルタリングをしていて、仲介するどれかが条件に合致しない場合、Django は空 (すべての値が NULL) だけど有効なオブジェクトとして扱います これが意味するのは、エラーが投げられないと言うことです。例えば、以下のフィルタでは:

Code
Blog.objects.filter(entry__authors__name="Lennon")

(関係づけられた Author モデルがあった場合で) entry に関係づけられた author がない場合、 name がなかったかのように扱われ、author がないという理由でエラーを投げることはありません。通常、これは必要とされる動作です。もし混乱するとしたら、isnull を使っている場合でしょう。なので:

Code
Blog.objects.filter(entry__authors__name__isnull=True)

これは author に空の name を持つ Blog オブジェクトと entry に空の author を返します。後者のオブジェクトがほしくない場合、以下のように書くことができます:

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

複数の値を持つリレーションの横断Link to this heading

When spanning a ManyToManyField or a reverse ForeignKey (such as from Blog to Entry), filtering on multiple attributes raises the question of whether to require each attribute to coincide in the same related object. We might seek blogs that have an entry from 2008 with “Lennon” in its headline, or we might seek blogs that merely have any entry from 2008 as well as some newer or older entry with “Lennon” in its headline.

To select all blogs containing at least one entry from 2008 having "Lennon" in its headline (the same entry satisfying both conditions), we would write:

Code
Blog.objects.filter(entry__headline__contains="Lennon", entry__pub_date__year=2008)

Otherwise, to perform a more permissive query selecting any blogs with merely some entry with "Lennon" in its headline and some entry from 2008, we would write:

Code
Blog.objects.filter(entry__headline__contains="Lennon").filter(
    entry__pub_date__year=2008
)

Suppose there is only one blog that has 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. (This is because 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.) In short, if each condition needs to match the same related object, then each should be contained in a single filter() call.

フィルターはモデルのフィールドを参照できるLink to this heading

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

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

For example, to find a list of all blog entries that have had more comments than pingbacks, we construct an F() object to reference the pingback count, and use that F() object in the query:

Python console
>>> from django.db.models import F
>>> Entry.objects.filter(number_of_comments__gt=F("number_of_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:

Python console
>>> Entry.objects.filter(number_of_comments__gt=F("number_of_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:

Python console
>>> Entry.objects.filter(rating__lt=F("number_of_comments") + F("number_of_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:

Python console
>>> Entry.objects.filter(authors__name=F("blog__name"))

For date and date/time fields, you can add or subtract a timedelta object. The following would return all entries that were modified more than 3 days after they were published:

Python console
>>> 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(), .bitxor(), .bitrightshift(), and .bitleftshift(). For example:

Python console
>>> F("somefield").bitand(16)

Expressions can reference transformsLink to this heading

Django supports using transforms in expressions.

For example, to find all Entry objects published in the same year as they were last modified:

Python console
>>> from django.db.models import F
>>> Entry.objects.filter(pub_date__year=F("mod_date__year"))

To find the earliest year an entry was published, we can issue the query:

Python console
>>> from django.db.models import Min
>>> Entry.objects.aggregate(first_published_year=Min("pub_date__year"))

This example finds the value of the highest rated entry and the total number of comments on all entries for each year:

Python console
>>> from django.db.models import OuterRef, Subquery, Sum
>>> Entry.objects.values("pub_date__year").annotate(
...     top_rating=Subquery(
...         Entry.objects.filter(
...             pub_date__year=OuterRef("pub_date__year"),
...         )
...         .order_by("-rating")
...         .values("rating")[:1]
...     ),
...     total_comments=Sum("number_of_comments"),
... )

pk ルックアップショートカットLink to this heading

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

In the example Blog model, the primary key is the id field, so these three statements are equivalent:

Python console
>>> 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:

Python console
# 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:

Python console
>>> 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 文の中ではパーセント記号とアンダースコアがエスケープされるLink to this heading

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, use the percent sign as any other character:

Python console
>>> 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.

キャッシングと QuerySetLink to this heading

それぞれの QuerySet には、データベースへのアクセスを最小にするために内部にキャッシュがあります。キャッシュのしくみを理解すれば、最も効率の良いコードが書けるようになります。

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

Keep this caching behavior in mind, because it may bite you if you don't use your QuerySets correctly. For example, the following will create two QuerySets, evaluate them, and throw them away:

Python console
>>> 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, save the QuerySet and reuse it:

Python console
>>> queryset = Entry.objects.all()
>>> print([p.headline for p in queryset])  # Evaluate the query set.
>>> print([p.pub_date for p in queryset])  # Reuse the cache from the evaluation.

QuerySet がキャッシュされない場合Link to this heading

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 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:

Python console
>>> 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:

Python console
>>> 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:

Python console
>>> [entry for entry in queryset]
>>> bool(queryset)
>>> entry in queryset
>>> list(queryset)

Asynchronous queriesLink to this heading

If you are writing asynchronous views or code, you cannot use the ORM for queries in quite the way we have described above, as you cannot call blocking synchronous code from asynchronous code - it will block up the event loop (or, more likely, Django will notice and raise a SynchronousOnlyOperation to stop that from happening).

Fortunately, you can do many queries using Django's asynchronous query APIs. Every method that might block - such as get() or delete() - has an asynchronous variant (aget() or adelete()), and when you iterate over results, you can use asynchronous iteration (async for) instead.

Query iterationLink to this heading

The default way of iterating over a query - with for - will result in a blocking database query behind the scenes as Django loads the results at iteration time. To fix this, you can swap to async for:

Code
async for entry in Authors.objects.filter(name__startswith="A"):
    ...

Be aware that you also can't do other things that might iterate over the queryset, such as wrapping list() around it to force its evaluation (you can use async for in a comprehension, if you want it).

Because QuerySet methods like filter() and exclude() do not actually run the query - they set up the queryset to run when it's iterated over - you can use those freely in asynchronous code. For a guide to which methods can keep being used like this, and which have asynchronous versions, read the next section.

QuerySet and manager methodsLink to this heading

Some methods on managers and querysets - like get() and first() - force execution of the queryset and are blocking. Some, like filter() and exclude(), don't force execution and so are safe to run from asynchronous code. But how are you supposed to tell the difference?

While you could poke around and see if there is an a-prefixed version of the method (for example, we have aget() but not afilter()), there is a more logical way - look up what kind of method it is in the QuerySet reference.

In there, you'll find the methods on QuerySets grouped into two sections:

  • Methods that return new querysets: These are the non-blocking ones, and don't have asynchronous versions. You're free to use these in any situation, though read the notes on defer() and only() before you use them.

  • Methods that do not return querysets: These are the blocking ones, and have asynchronous versions - the asynchronous name for each is noted in its documentation, though our standard pattern is to add an a prefix.

Using this distinction, you can work out when you need to use asynchronous versions, and when you don't. For example, here's a valid asynchronous query:

Code
user = await User.objects.filter(username=my_input).afirst()

filter() returns a queryset, and so it's fine to keep chaining it inside an asynchronous environment, whereas first() evaluates and returns a model instance - thus, we change to afirst(), and use await at the front of the whole expression in order to call it in an asynchronous-friendly way.

TransactionsLink to this heading

Transactions are not currently supported with asynchronous queries and updates. You will find that trying to use one raises SynchronousOnlyOperation.

If you wish to use a transaction, we suggest you write your ORM code inside a separate, synchronous function and then call that using sync_to_async - see 非同期サポート for more.

Querying JSONFieldLink to this heading

Lookups implementation is different in JSONField, mainly due to the existence of key transformations. To demonstrate, we will use the following example model:

Code
from django.db import models


class Dog(models.Model):
    name = models.CharField(max_length=200)
    data = models.JSONField(null=True)

    def __str__(self):
        return self.name

Storing and querying for NoneLink to this heading

As with other fields, storing None as the field's value will store it as SQL NULL. While not recommended, it is possible to store JSON scalar null instead of SQL NULL by using Value(None, JSONField()).

Whichever of the values is stored, when retrieved from the database, the Python representation of the JSON scalar null is the same as SQL NULL, i.e. None. Therefore, it can be hard to distinguish between them.

This only applies to None as the top-level value of the field. If None is inside a list or dict, it will always be interpreted as JSON null.

When querying, None value will always be interpreted as JSON null. To query for SQL NULL, use isnull:

Python console
>>> Dog.objects.create(name="Max", data=None)  # SQL NULL.
<Dog: Max>
>>> Dog.objects.create(name="Archie", data=Value(None, JSONField()))  # JSON null.
<Dog: Archie>
>>> Dog.objects.filter(data=None)
<QuerySet [<Dog: Archie>]>
>>> Dog.objects.filter(data=Value(None, JSONField()))
<QuerySet [<Dog: Archie>]>
>>> Dog.objects.filter(data__isnull=True)
<QuerySet [<Dog: Max>]>
>>> Dog.objects.filter(data__isnull=False)
<QuerySet [<Dog: Archie>]>

Unless you are sure you wish to work with SQL NULL values, consider setting null=False and providing a suitable default for empty values, such as default=dict.

Key, index, and path transformsLink to this heading

To query based on a given dictionary key, use that key as the lookup name:

Python console
>>> Dog.objects.create(
...     name="Rufus",
...     data={
...         "breed": "labrador",
...         "owner": {
...             "name": "Bob",
...             "other_pets": [
...                 {
...                     "name": "Fishy",
...                 }
...             ],
...         },
...     },
... )
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": None})
<Dog: Meg>
>>> Dog.objects.filter(data__breed="collie")
<QuerySet [<Dog: Meg>]>

Multiple keys can be chained together to form a path lookup:

Python console
>>> Dog.objects.filter(data__owner__name="Bob")
<QuerySet [<Dog: Rufus>]>

If the key is an integer, it will be interpreted as an index transform in an array:

Python console
>>> Dog.objects.filter(data__owner__other_pets__0__name="Fishy")
<QuerySet [<Dog: Rufus>]>

If the key you wish to query by clashes with the name of another lookup, use the contains lookup instead.

To query for missing keys, use the isnull lookup:

Python console
>>> Dog.objects.create(name="Shep", data={"breed": "collie"})
<Dog: Shep>
>>> Dog.objects.filter(data__owner__isnull=True)
<QuerySet [<Dog: Shep>]>

KT() expressionsLink to this heading

class KT(lookup)Link to this definition

Represents the text value of a key, index, or path transform of JSONField. You can use the double underscore notation in lookup to chain dictionary key and index transforms.

例えば:

Python console
>>> from django.db.models.fields.json import KT
>>> Dog.objects.create(
...     name="Shep",
...     data={
...         "owner": {"name": "Bob"},
...         "breed": ["collie", "lhasa apso"],
...     },
... )
<Dog: Shep>
>>> Dogs.objects.annotate(
...     first_breed=KT("data__breed__1"), owner_name=KT("data__owner__name")
... ).filter(first_breed__startswith="lhasa", owner_name="Bob")
<QuerySet [<Dog: Shep>]>

Containment and key lookupsLink to this heading

containsLink to this heading

The contains lookup is overridden on JSONField. The returned objects are those where the given dict of key-value pairs are all contained in the top-level of the field. For example:

Python console
>>> Dog.objects.create(name="Rufus", data={"breed": "labrador", "owner": "Bob"})
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
<Dog: Meg>
>>> Dog.objects.create(name="Fred", data={})
<Dog: Fred>
>>> Dog.objects.filter(data__contains={"owner": "Bob"})
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
>>> Dog.objects.filter(data__contains={"breed": "collie"})
<QuerySet [<Dog: Meg>]>

contained_byLink to this heading

This is the inverse of the contains lookup - the objects returned will be those where the key-value pairs on the object are a subset of those in the value passed. For example:

Python console
>>> Dog.objects.create(name="Rufus", data={"breed": "labrador", "owner": "Bob"})
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
<Dog: Meg>
>>> Dog.objects.create(name="Fred", data={})
<Dog: Fred>
>>> Dog.objects.filter(data__contained_by={"breed": "collie", "owner": "Bob"})
<QuerySet [<Dog: Meg>, <Dog: Fred>]>
>>> Dog.objects.filter(data__contained_by={"breed": "collie"})
<QuerySet [<Dog: Fred>]>

has_keyLink to this heading

Returns objects where the given key is in the top-level of the data. For example:

Python console
>>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
<Dog: Meg>
>>> Dog.objects.filter(data__has_key="owner")
<QuerySet [<Dog: Meg>]>

has_keysLink to this heading

Returns objects where all of the given keys are in the top-level of the data. For example:

Python console
>>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
<Dog: Meg>
>>> Dog.objects.filter(data__has_keys=["breed", "owner"])
<QuerySet [<Dog: Meg>]>

has_any_keysLink to this heading

Returns objects where any of the given keys are in the top-level of the data. For example:

Python console
>>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"owner": "Bob"})
<Dog: Meg>
>>> Dog.objects.filter(data__has_any_keys=["owner", "breed"])
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>

Q オブジェクトを用いた複雑な検索Link to this heading

Keyword argument queries -- in 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.

A Q object (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 クエリをカプセル化しています。

Code
from django.db.models import Q

Q(question__startswith="What")

Q objects can be combined using the &, |, and ^ operators. When an operator is used on two Q objects, it yields a new Q object.

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

Code
Q(question__startswith="Who") | Q(question__startswith="What")

This is equivalent to the following SQL WHERE clause:

SQL
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:

Code
Q(question__startswith="Who") | ~Q(pub_date__year=2005)

Each lookup function that takes keyword-arguments (e.g. filter(), exclude(), 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:

Code
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:

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:

Code
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:

Code
# 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.

オブジェクトを比較するLink to this heading

To compare two model instances, 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:

Python console
>>> 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:

Python console
>>> some_obj == other_obj
>>> some_obj.name == other_obj.name

オブジェクトを削除するLink to this heading

The delete method, conveniently, is named 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:

Python console
>>> e.delete()
(1, {'blog.Entry': 1})

オブジェクトを一括で削除することもできます。すべての QuerySetdelete() メソッドを持っており、その QuerySet のすべてのメンバーを削除します。

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

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

注意してほしいのは、この処理は可能な場合には純粋に SQL で実行され、個別のオブジェクトインスタンスの delete() メソッドはプロセス中に呼ぶ必要はないということです。モデルクラスで独自の delete() メソッドを定義していて確実に呼び出されるようにしたい場合、QuerySet で一括の delete() を使用するのではなく、そのモデルのインスタンスを "手動で" 削除する必要があります (例えば、QuerySet を繰り返し処理し、各オブジェクトで個別に delete() を呼び出します)。

Django がオブジェクトを削除するとき、デフォルトでは SQL の制限 ON DELETE CASCADE の動作をエミュレートします -- 言い換えると、削除するオブジェクトを指している外部キーを持つすべてのオブジェクトは、ともに削除されることになります。例えば:

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

このカスケードの動作は、ForeignKey に対する on_delete 属性によってカスタマイズできます。

delete() は、Manager で露出していない唯一の QuerySet のメソッドです。これは、Entry.objects.delete() を誤ってリクエストして すべての entry を削除してしまうことを防ぐ安全上の仕組みです。すべてのオブジェクトを削除 したい 場合、明示的に完全なクエリセットをリクエストする必要があります:

Code
Entry.objects.all().delete()

モデルのインスタンスを複製するLink to this heading

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 set pk to None and _state.adding to True. Using our blog example:

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

blog.pk = None
blog._state.adding = True
blog.save()  # blog.pk == 2

継承を使用している場合、物事は少し複雑になります。Blog のサブクラスを考えると:

Code
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, and _state.adding to True:

Code
django_blog.pk = None
django_blog.id = None
django_blog._state.adding = True
django_blog.save()  # django_blog.pk == 4

この処理では、モデルのデータベーステーブルの一部ではないリレーションは複製しません。例えば、EntryAuthor への ManyToManyField を持ちます。entry の複製後、新しい entry に対して多対多のリレーションをセットする必要があります:

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

OneToOneField については、1 対 1 のユニーク制限への違反を避けるため、関係オブジェクトを複製して新しいオブジェクトのフィールドに割り当てる必要があります。例えば、entry が上記のようにすでに複製されているものとすると:

Code
detail = EntryDetail.objects.all()[0]
detail.pk = None
detail._state.adding = True
detail.entry = entry
detail.save()

複数のオブジェクトを一括で更新するLink to this heading

QuerySet のすべてのオブジェクトに、特定の値をセットしたい場合があります。update() を使えば実現できます。例えば:

Code
# 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 fields using this method. To update a non-relation field, provide the new value as a constant. To update ForeignKey fields, set the new value to be the new model instance you want to point to. For example:

Python console
>>> b = Blog.objects.get(pk=1)

# Change every Entry so that it belongs to this Blog.
>>> Entry.objects.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 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:

Python console
>>> b = Blog.objects.get(pk=1)

# Update all the headlines belonging to this Blog.
>>> Entry.objects.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() methods on your models, or emit the pre_save or post_save signals (which are a consequence of calling save()), or honor the auto_now field option. If you want to save every item in a QuerySet and make sure that the save() method is called on each instance, you don't need any special function to handle that. Loop over them and call save():

Code
for item in my_queryset:
    item.save()

Calls to update can also use F expressions 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:

Python console
>>> Entry.objects.update(number_of_pingbacks=F("number_of_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:

Python console
# This will raise a FieldError
>>> Entry.objects.update(headline=F("blog__name"))

素の SQL にフォールバックするLink to this heading

Django のデータベースマッパが扱うには複雑すぎる SQL クエリを記述する必要がある場合、手書きで SQL を書くことができます。Django には、素の SQL クエリを記述するための方法がいくつかあります; 素の SQL 文の実行 を参照してください。

最後に、覚えておいてほしい重要な点は、Django のデータベースレイヤはあなたのデータベースに対する単なるインターフェースでしかないということです。あなたは、他のツール、プログラミング言語、データベースフレームワークなどを通じてデータベースを操作することもできます; データベースに関して Django 特有のことは何もありません。