Skip to content
Browse files

Fixed #16856 - Added a way to clear select_related.

Thanks Carl for the suggestion and David Cramer for the patch.
  • Loading branch information...
1 parent 616f3c4 commit 5074c75a37f88726f3ae057999144545881d3cfc @timgraham timgraham committed
6 django/db/models/
@@ -645,6 +645,8 @@ def select_related(self, *fields, **kwargs):
If fields are specified, they must be ForeignKey fields and only those
related objects are included in the selection.
+ If select_related(None) is called, the list is cleared.
if 'depth' in kwargs:
warnings.warn('The "depth" keyword argument has been deprecated.\n'
@@ -654,7 +656,9 @@ def select_related(self, *fields, **kwargs):
raise TypeError('Unexpected keyword arguments to select_related: %s'
% (list(kwargs),))
obj = self._clone()
- if fields:
+ if fields == (None,):
+ obj.query.select_related = False
+ elif fields:
if depth:
raise TypeError('Cannot pass both "depth" and fields to select_related()')
7 docs/ref/models/querysets.txt
@@ -774,6 +774,13 @@ You can also refer to the reverse direction of a
is defined. Instead of specifying the field name, use the :attr:`related_name
<django.db.models.ForeignKey.related_name>` for the field on the related object.
+.. versionadded:: 1.6
+If you need to clear the list of related fields added by past calls of
+``select_related`` on a ``QuerySet``, you can pass ``None`` as a parameter::
+ >>> without_relations = queryset.select_related(None)
.. deprecated:: 1.5
The ``depth`` parameter to ``select_related()`` has been deprecated. You
should replace it with the use of the ``(*fields)`` listing specific
5 docs/releases/1.6.txt
@@ -287,6 +287,11 @@ Minor features
helper for testing formset errors:
+* The list of related fields added to a
+ :class:`~django.db.models.query.QuerySet` by
+ :meth:`~django.db.models.query.QuerySet.select_related` can be cleared using
+ ``select_related(None)``.
Backwards incompatible changes in 1.6
4 tests/select_related/
@@ -172,3 +172,7 @@ def test_depth_fields_fails(self):
'genus__family__order', depth=4
+ def test_none_clears_list(self):
+ queryset = Species.objects.select_related('genus').select_related(None)
+ self.assertEqual(queryset.query.select_related, False)

0 comments on commit 5074c75

Please sign in to comment.
Something went wrong with that request. Please try again.