Fixed #25252 -- Added friendly error message on incorrect .select_related() use

Using select_related() after .values() or .values_list() is not possible
because .values() or .values_list() already got the values they need.
This commit is contained in:
Y3K 2015-08-30 23:18:03 -05:00 committed by Josh Smeaton
parent 7a98442f96
commit cbcf78fa94
2 changed files with 24 additions and 0 deletions

View File

@ -843,6 +843,10 @@ class QuerySet(object):
If select_related(None) is called, the list is cleared.
"""
if self._fields is not None:
raise TypeError("Cannot call select_related() after .values() or .values_list()")
obj = self._clone()
if fields == (None,):
obj.query.select_related = False

View File

@ -163,6 +163,26 @@ class SelectRelatedTests(TestCase):
self.assertEqual(obj.parent_1, parent_1)
self.assertEqual(obj.parent_2, parent_2)
def test_select_related_after_values(self):
"""
Running select_related() after calling values() raises a TypeError
"""
message = "Cannot call select_related() after .values() or .values_list()"
with self.assertRaisesMessage(TypeError, message):
list(Species.objects.values('name').select_related('genus'))
def test_select_related_after_values_list(self):
"""
Running select_related() after calling values_list() raises a TypeError
"""
message = "Cannot call select_related() after .values() or .values_list()"
with self.assertRaisesMessage(TypeError, message):
list(Species.objects.values_list('name').select_related('genus'))
class SelectRelatedValidationTests(SimpleTestCase):
"""