id summary reporter owner description type status component version severity resolution keywords cc stage has_patch needs_docs needs_tests needs_better_patch easy ui_ux 28551 Exclude query on M2M field with F() fails daishi nobody "Given the following models: {{{ class A(models.Model): pass class B(models.Model): a = models.ManyToManyField(A) class C(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) }}} The following test: {{{ a1 = A() a1.save() a2 = A() a2.save() b1 = B() b1.save() b1.a.add(a1) b1.save() b2 = B() b2.save() b2.a.add(a2) b2.save() c1 = C(a=a1, b=b1) c1.save() c2 = C(a=a1, b=b2) c2.save() self.assertEqual(1, C.objects.filter(b__a=F('a')).count()) self.assertEqual(1, C.objects.exclude(b__a=F('a')).count()) }}} Fails with the following error: {{{ OperationalError: no such column: U2.id }}} The SQL generated by Django for the `C.objects.exclude(b__a=F('a'))` fragment is logged as: {{{ SELECT ""a_c"".""id"", ""a_c"".""a_id"", ""a_c"".""b_id"" FROM ""a_c"" WHERE NOT (""a_c"".""b_id"" IN (SELECT U3.""b_id"" AS Col1 FROM ""a_c"" U0 INNER JOIN ""a_b_a"" U3 ON (U2.""id"" = U3.""b_id"") WHERE U3.""a_id"" = (U0.""a_id""))) LIMIT 21; args=() }}} As suggested in the error, the `U2` join table does not seem to be defined in the generated query." Bug closed Database layer (models, ORM) 1.11 Normal duplicate Unreviewed 0 0 0 0 0 0