diff options
| author | Tim Graham <timograham@gmail.com> | 2012-11-02 06:54:00 -0400 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2012-11-02 17:58:24 -0400 |
| commit | feaf9f279a73d87549c17fc7fb36463f1c7367a1 (patch) | |
| tree | d634f3f36222c58ebd7eca43f1fc5e3fbc4befb5 /docs | |
| parent | 92fc263a2898b804c3b46447fd47e2898fbf8ff1 (diff) | |
Fixed #15361 - Documented performance considerations for QuerySet.get()
Thanks mmcnickle for the patch.
Diffstat (limited to 'docs')
| -rw-r--r-- | docs/topics/db/optimization.txt | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/docs/topics/db/optimization.txt b/docs/topics/db/optimization.txt index 772792d39d..b5cca52e23 100644 --- a/docs/topics/db/optimization.txt +++ b/docs/topics/db/optimization.txt @@ -132,6 +132,41 @@ Write your own :doc:`custom SQL to retrieve data or populate models </topics/db/sql>`. Use ``django.db.connection.queries`` to find out what Django is writing for you and start from there. +Retrieve individual objects using a unique, indexed column +========================================================== + +There are two reasons to use a column with +:attr:`~django.db.models.Field.unique` or +:attr:`~django.db.models.Field.db_index` when using +:meth:`~django.db.models.query.QuerySet.get` to retrieve individual objects. +First, the query will be quicker because of the underlying database index. +Also, the query could run much slower if multiple objects match the lookup; +having a unique constraint on the column guarantees this will never happen. + +So using the :ref:`example Weblog models <queryset-model-example>`:: + + >>> entry = Entry.objects.get(id=10) + +will be quicker than: + + >>> entry = Entry.object.get(headline="News Item Title") + +because ``id`` is indexed by the database and is guaranteed to be unique. + +Doing the following is potentially quite slow: + + >>> entry = Entry.objects.get(headline__startswith="News") + +First of all, `headline` is not indexed, which will make the underlying +database fetch slower. + +Second, the lookup doesn't guarantee that only one object will be returned. +If the query matches more than one object, it will retrieve and transfer all of +them from the database. This penalty could be substantial if hundreds or +thousands of records are returned. The penalty will be compounded if the +database lives on a separate server, where network overhead and latency also +play a factor. + Retrieve everything at once if you know you will need it ======================================================== |
