mirror of
https://github.com/django/django.git
synced 2025-10-24 14:16:09 +00:00
queryset-refactor: Allow specifying of specific relations to follow in
select_related(). Refs #5020. git-svn-id: http://code.djangoproject.com/svn/django/branches/queryset-refactor@6899 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
@@ -744,8 +744,8 @@ related ``Person`` *and* the related ``City``::
|
||||
p = b.author # Hits the database.
|
||||
c = p.hometown # Hits the database.
|
||||
|
||||
Note that ``select_related()`` does not follow foreign keys that have
|
||||
``null=True``.
|
||||
Note that, by default, ``select_related()`` does not follow foreign keys that
|
||||
have ``null=True``.
|
||||
|
||||
Usually, using ``select_related()`` can vastly improve performance because your
|
||||
app can avoid many database calls. However, in situations with deeply nested
|
||||
@@ -762,6 +762,41 @@ follow::
|
||||
|
||||
The ``depth`` argument is new in the Django development version.
|
||||
|
||||
**New in Django development version:** Sometimes you only need to access
|
||||
specific models that are related to your root model, not all of the related
|
||||
models. In these cases, you can pass the related field names to
|
||||
``select_related()`` and it will only follow those relations. You can even do
|
||||
this for models that are more than one relation away by separating the field
|
||||
names with double underscores, just as for filters. For example, if we have
|
||||
thise model::
|
||||
|
||||
class Room(models.Model):
|
||||
# ...
|
||||
building = models.ForeignKey(...)
|
||||
|
||||
class Group(models.Model):
|
||||
# ...
|
||||
teacher = models.ForeignKey(...)
|
||||
room = models.ForeignKey(Room)
|
||||
subject = models.ForeignKey(...)
|
||||
|
||||
...and we only needed to work with the ``room`` and ``subject`` attributes, we
|
||||
could write this::
|
||||
|
||||
g = Group.objects.select_related('room', 'subject')
|
||||
|
||||
This is also valid::
|
||||
|
||||
g = Group.objects.select_related('room__building', 'subject')
|
||||
|
||||
...and would also pull in the ``building`` relation.
|
||||
|
||||
You can only refer to ``ForeignKey`` relations in the list of fields passed to
|
||||
``select_related``. You *can* refer to foreign keys that have ``null=True``
|
||||
(unlike the default ``select_related()`` call). It's an error to use both a
|
||||
list of fields and the ``depth`` parameter in the same ``select_related()``
|
||||
call, since they are conflicting options.
|
||||
|
||||
``extra(select=None, where=None, params=None, tables=None, order_by=None)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
Reference in New Issue
Block a user