@@ -9,28 +9,24 @@ QuerySet API リファレンス
9
9
10
10
.. currentmodule:: django.db.models
11
11
12
- .. TBD
12
+ このドキュメントでは、 クエリセット(``QuerySet``) API について詳しく解説し
13
+ ます。このドキュメントは、 :ref:`モデル <topics-db-models>` と
14
+ :ref:`データベースクエリ <topics-db-queries>` に基づいて書かれているので、
15
+ あらかじめ読んでおくよう勧めます。
13
16
14
- This document describes the details of the ``QuerySet`` API. It builds on the
15
- material presented in the :ref:`model <topics-db-models>` and `database query
16
- <topics-db-queries>` guides, so you'll probably want to read and understand
17
- those documents before reading this one.
18
-
19
- Throughout this reference we'll use the :ref:`example weblog models
20
- <queryset-model-example>` presented in the :ref:`database query guide
21
- <topics-db-queries>`.
17
+ このリファレンスを通じて、例題には :ref:`データベースクエリガイド
18
+ <topics-db-queries>` で取り上げた :ref:`ブログのモデル例
19
+ <queryset-model-example>` を使います。
22
20
23
21
.. _when-querysets-are-evaluated:
24
22
.. _When QuerySets are evaluated:
25
23
26
24
クエリセットはいつ評価されるのか
27
25
=================================
28
26
29
- .. TBD
30
-
31
- Internally, a ``QuerySet`` can be constructed, filter, sliced, and generally
32
- passed around without actually hitting the database. No database activity
33
- actually occurs until you do something to evaluate the queryset.
27
+ 内部的には、クエリセットの生成、フィルタ操作、スライス、コード間の受渡しは、
28
+ データベースを操作することなく行えます。クエリセットを何らかの形で評価しな
29
+ い限り、データベースの操作は実際には起こらないのです。
34
30
35
31
以下の方法を使うと、クエリセットを評価できます:
36
32
@@ -75,17 +71,17 @@ actually occurs until you do something to evaluate the queryset.
75
71
76
72
.. _queryset-api:
77
73
78
- QuerySet API
79
- ============
74
+ クエリセット API
75
+ =================
80
76
81
- .. TBD
82
-
83
- Though you usually won't create one manually -- you'll go through a :class:`Manager` -- here's the formal declaration of a ``QuerySet``:
77
+ クエリセットは手動で作成できません (:class:`Manager` を介してしか生成できま
78
+ せん) が、 ``QuerysSet`` クラスのコンストラクタの正式な定義は以下の通りです:
84
79
85
80
.. class:: QuerySet([model=None])
86
81
87
- Usually when you'll interact with a ``QuerySet`` you'll use it by :ref:`chaining
88
- filters <chaining-filters>`. To make this work, most ``QuerySet`` methods return new querysets.
82
+ 通常、クエリセットを操作するときには、 :ref:`フィルタを連鎖
83
+ <chaining-filters>` させます。クエリセットに対するフィルタ操作は、ほとんど
84
+ が新たなクエリセットを返します。
89
85
90
86
.. _QuerySet methods that return new QuerySets:
91
87
@@ -178,19 +174,17 @@ Django はリレーション先のモデルのデフォルトの整列順 (``Met
178
174
179
175
Entry.objects.order_by('blog__id')
180
176
181
- ..TBD
182
-
183
- Be cautious when ordering by fields in related models if you are also using
184
- ``distinct()``. See the note in the `distinct()`_ section for an explanation
185
- of how related model ordering can change the expected results.
177
+ リレーション先のモデルのフィールドを使った整列と ``distinct()`` を組み合わ
178
+ せる場合は注意が必要です。リレーション先のモデルの整列が、 ``distinct()``
179
+ によってどのように影響を受けるかは、 `distinct()`_ の説明を参照してください。
186
180
187
- It is permissible to specify a multi-valued field to order the results by (for
188
- example, a ``ManyToMany`` field). Normally this won't be a sensible thing to
189
- do and it's really an advanced usage feature. However, if you know that your
190
- queryset's filtering or available data implies that there will only be one
191
- ordering piece of data for each of the main items you are selecting, the
192
- ordering may well be exactly what you want to do. Use ordering on multi-valued
193
- fields with care and make sure the results are what you expect.
181
+ クエリ結果の整列には、 (``ManyToMany`` のような)複数の値で構成されるフィー
182
+ ルドも指定できます。通常、こうした指定にはあまり意味がなく、本当に高度な使
183
+ い方です。しかし、クエリセットをフィルタした結果や、もともとのデータにおい
184
+ て、リレーション元のオブジェクトから参照しているオブジェクトが一つしかない
185
+ ことが暗黙的に決まっているとはっきりしていれば、整列結果は期待通りになるで
186
+ しょう。複数の値で構成されるフィールドで整列を行う場合には、十分注意して、
187
+ 期待通りの結果が得られるか確認してください。
194
188
195
189
.. versionadded:: 1.0
196
190
@@ -209,16 +203,12 @@ fields with care and make sure the results are what you expect.
209
203
字の区別については、 Django は現在使っているデータベースバックエンドの整列
210
204
方法に従います。
211
205
212
- .. TBD
213
-
214
- Also, note that ``reverse()`` should generally only be called on a
215
- ``QuerySet`` which has a defined ordering (e.g., when querying against
216
- a model which defines a default ordering, or when using
217
- ``order_by()``). If no such ordering is defined for a given
218
- ``QuerySet``, calling ``reverse()`` on it has no real effect (the
219
- ordering was undefined prior to calling ``reverse()``, and will remain
220
- undefined afterward).
221
-
206
+ また、 ``reverse()`` は一般に、すでに整列方法の定義されているクエリセット
207
+ (デフォルトの整列順の定義されたモデルから取り出したクエリセットや、
208
+ ``order_by()`` で整列されたもの) に対して呼びだすべきものです。整列方法の定
209
+ 義されていないクエリセットに対して ``reverse()`` を呼び出しても、何ら効果
210
+ をもたらしません (``reverse()`` を呼び出す前に整列方法が定義されていなけれ
211
+ ば、呼び出した後の整列方法も未定義のままです)。
222
212
223
213
``distinct()``
224
214
~~~~~~~~~~~~~~
@@ -564,13 +554,11 @@ Django の作者たちは、全ての SQL 関係のメソッドを先に配置
564
554
select=SortedDict([('a', '%s'), ('b', '%s')]),
565
555
select_params=('one', 'two'))
566
556
567
- .. TBD
568
-
569
- The only thing to be careful about when using select parameters in
570
- ``extra()`` is to avoid using the substring ``"%%s"`` (that's *two*
571
- percent characters before the ``s``) in the select strings. Django's
572
- tracking of parameters looks for ``%s`` and an escaped ``%`` character
573
- like this isn't detected. That will lead to incorrect results.
557
+ ``extra()`` に SELECT パラメタを渡す時には、 ``"%%s"`` (``s`` の前のパー
558
+ セント記号が *二重* のもの) だけは使わないでください。 Django は
559
+ ``%s`` を探してパラメタの挿入位置を追跡しますが、 ``"%%s"`` のように
560
+ ``%`` がエスケープされていると検出しないからです。そのため、クエリ結果
561
+ が正しくなくなります。
574
562
575
563
``where`` / ``tables``
576
564
明示的に追加の ``WHERE`` 節を渡す必要がある場合 -- おそらく非明示的な結
@@ -670,9 +658,8 @@ QuerySet を返さないクエリセットメソッド
670
658
照合パラメタに一致するオブジェクトを返します。照合パラメタは後述の
671
659
`フィールドの照合`_ で説明するフォーマットにします。
672
660
673
- .. TBD
674
-
675
- ``get()`` raises ``AssertionError`` if more than one object was found.
661
+ 複数のオブジェクトがみつかると、 ``get()`` は ``AssertionError`` を送出しま
662
+ す。
676
663
677
664
指定パラメタに対するオブジェクトが見つからなかった場合には ``get()`` は
678
665
``DoesNotExist`` 例外を送出します。 ``DoesNotExist`` 例外はモデルクラスの属
@@ -706,15 +693,13 @@ QuerySet を返さないクエリセットメソッド
706
693
707
694
は等価です。
708
695
709
- .. TBD
710
-
711
- The :ref:`force_insert <ref-models-force-insert>` parameter is documented
712
- elsewhere, but all it means is that a new object will always be created.
713
- Normally you won't need to worry about this. However, if your model contains a
714
- manual primary key value that you set and if that value already exists in the
715
- database, a call to ``create()`` will fail with an ``IntegrityError`` since
716
- primary keys must be unique. So remember to be prepared to handle the
717
- exception if you are using manual primary keys.
696
+ :ref:`force_insert <ref-models-force-insert>` パラメタはここでは説明してい
697
+ ませんが、このパラメタを指定すると、常に新たなオブジェクトを生成します。
698
+ 通常は、このパラメタのことを気にする必要はありません。しかし、モデルに手動
699
+ で設定した主キーが存在していて、すでにデータベース上にある主キーと同じ値を
700
+ もったオブジェクトを ``create()`` して保存しようとすると、主キーの一意性が
701
+ 破れてしまうため、 ``IntegrityError`` を引き起こしてしまいます。ですから、
702
+ 手動で主キーを設定したときには、例外処理を忘れずに準備しておいてください。
718
703
719
704
``get_or_create(**kwargs)``
720
705
~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -755,29 +740,24 @@ kwargs に指定したオブジェクトを照合し、なければ生成する
755
740
obj = self.model(**params)
756
741
obj.save()
757
742
758
- .. TBD
759
-
760
743
上のコードを日本語で表すなら、まず ``'defaults'`` でないキーワード引数のう
761
744
ち、二重アンダースコアを含まないもの (二重アンダースコアはあいまい照合のキー
762
745
ワードなので除外します) を使ってパラメタ ``params`` を作成し、必要に応じて
763
746
デフォルト値 ``defaults`` で内容を更新して、その結果をモデルクラスを呼び出
764
- すときのキーワード引数に使います。 As hinted at
765
- above, this is a simplification of the algorithm that is used, but it contains
766
- all the pertinent details. The internal implementation has some more
767
- error-checking than this and handles some extra edge-conditions; if you're
768
- interested, read the code.
747
+ すときのキーワード引数に使う、という処理に相当します。上で示唆したように、
748
+ ここではアルゴリズムを簡単化して、必要な部分だけを記述しています。内部実装
749
+ では、もっと細かくエラーチェックを行い、境界条件を処理しています。興味があ
750
+ るなら、ぜひコードを読んでみてください。
769
751
770
752
``defaults`` という名前のフィールド名を持っていて、 ``get_or_create()`` の
771
753
中で厳密照合に使いたければ、以下のように ``'defaults__exact'`` を使います::
772
754
773
755
Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'})
774
756
775
- .. TBD
776
-
777
- The ``get_or_create()`` method has similar error behaviour to ``create()``
778
- when you are using manually specified primary keys. If an object needs to be
779
- created and the key already exists in the database, an ``IntegrityError`` will
780
- be raised.
757
+ 主キーを手動で指定している場合、 ``get_or_create()`` メソッドは
758
+ ``create()`` とおなじようなエラーを引き起こします。すなわち、すでにデータベー
759
+ ス上に存在するキーを使ってオブジェクトを生成しようとすると、
760
+ ``IntegrityError`` を送出します。
781
761
782
762
最後に、 Django ビューの中で ``get_or_create()`` を使う場合についてひとこと
783
763
注意しておきましょう。上で説明したように、主として ``get_or_create()`` が有
@@ -869,19 +849,18 @@ be raised.
869
849
870
850
``latest()`` は純粋に利便性と可読性のためだけに存在しています。
871
851
872
- .. TBD
873
-
874
852
.. _field-lookups:
875
853
.. Field lookups
876
854
877
855
フィールドの照合
878
856
----------------
879
857
880
- Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
881
- specified as keyword arguments to the ``QuerySet `` methods ``filter ()``,
882
- ``exclude()`` and ``get()``.
858
+ フィールドの照合操作によって、 SQL の ``WHERE`` 節の中身が決まります。フィー
859
+ ルドの照合を行うには、 ``filter()``, ``exclude() `` および ``get ()`` といっ
860
+ たクエリセットのメソッドのキーワード引数を指定します。
883
861
884
- For an introduction, see :ref:`field-lookups-intro`.
862
+ フィールド照合について知りたければ、 :ref:`field-lookups-intro` を参照して
863
+ ください。
885
864
886
865
exact
887
866
~~~~~
@@ -906,17 +885,15 @@ exact
906
885
いましたが、この SQL はいかなるレコードにもマッチしません。バージョン
907
886
1.0 では、 ``id__isnull=True`` と同じ挙動を示すように変更されています。
908
887
909
- .. TBD
910
-
911
- .. admonition:: MySQL comparisons
888
+ .. admonition:: MySQL での比較
912
889
913
- In MySQL, whether or not ``exact`` comparisons are case-insensitive by
914
- default. This is controlled by the collation setting on the database
915
- tables (this is a database setting, *not* a Django setting). It is
916
- possible to configured you MySQL tables to use case-sensitive comparisons,
917
- however there are some trade-offs involved. For more information about
918
- this, see the :ref:`collation section <mysql-collation >` in the
919
- :ref:`databases <ref-databases >` documentation.
890
+ MySQL では、デフォルト構成での ``exact`` 比較の判定は大小文字を区別しま
891
+ せん。大小文字の区別は、データベーステーブルごとのコレーション
892
+ (collation) 設定で制御されています (データベースの設定であって、 Django
893
+ の設定では *ありません*)。 MySQL のテーブルは大小文字を区別して比較する
894
+ ように構成できますが、トレードオフもあります。詳しくは、
895
+ :ref:`databases <ref-databases >` ドキュメントの :ref:`コレーションの節
896
+ <mysql-collation >` を参照してください。
920
897
921
898
iexact
922
899
~~~~~~
990
967
q = Blog.objects.filter(name__contains='Cheddar').values('pk').query
991
968
e = Entry.objects.filter(blog__in=q)
992
969
993
- .. TBD
994
-
995
970
.. warning::
996
971
997
- This ``query`` attribute should be considered an opaque internal attribute.
998
- It's fine to use it like above, but its API may change between Django
999
- versions.
972
+ ``query`` 属性は、まだ明確に仕様の定まっていない内部的な属性です。
973
+ 現在は上記のように問題なく使えますが、将来のバージョンで API が変更され
974
+ るかもしれません。
1000
975
1001
976
上のクエリセットを評価すると、以下の SQL 文と同様の結果を得ます::
1002
977
@@ -1153,8 +1128,6 @@ date/datetime フィールドに対する day の厳密一致です。
1153
1128
1154
1129
SELECT ... WHERE EXTRACT('day' FROM pub_date) = '3';
1155
1130
1156
- (The exact SQL syntax varies for each database engine.)
1157
-
1158
1131
(厳密な SQL シンタクスはデータベースエンジンによって違います。)
1159
1132
1160
1133
このクエリ文は、「1 月 3 日」や「7 月 3 日」のように、毎月 3 日にマッチし
@@ -1174,13 +1147,13 @@ isnull
1174
1147
1175
1148
SELECT ... WHERE pub_date IS NULL;
1176
1149
1177
- .. admonition:: ``__isnull=True`` vs ``__exact=None``
1150
+ .. admonition:: ``__isnull=True`` と ``__exact=None``
1178
1151
1179
- There is an important difference between ``__isnull=True`` and
1180
- ``__exact=None``. ``__exact=None `` will *always* return an empty result
1181
- set, because SQL requires that no value is equal to ``NULL``.
1182
- ``__isnull`` determines if the field is currently holding the value
1183
- of ``NULL`` without performing a comparison.
1152
+ ``__isnull=True`` と ``__exact=None`` には重要な違いがあります。
1153
+ SQL の仕様上、いかなる値も ``NULL `` と等価ではないので、
1154
+ ``__exact=None`` は *常に* 空の結果セットを返します。一方、
1155
+ ``__isnull`` はフィールドの値が ``NULL`` であるかどうかだけを調べ、比較
1156
+ を実行しません。
1184
1157
1185
1158
search
1186
1159
~~~~~~
0 commit comments