--- django/tests/m2m_through/tests.py
+++ django/tests/m2m_through/tests.py
@@ -343,3 +343,11 @@ class M2mThroughTests(TestCase):
             ],
             attrgetter("name")
         )
+
+    def test_ticket_20535_join_trimming(self):
+        qs = Friendship.objects.filter(first__rel_to_set__first__id=1)
+        self.assertEqual(str(qs.query).count('JOIN'), 1)
+
+    def test_ticket_20535_no_join_trimming(self):
+        qs = Friendship.objects.filter(first__rel_to_set__first__id=1, first__name='Jane')
+        self.assertEqual(str(qs.query).count('JOIN'), 2)
