﻿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
19672	Negated Q objects over nullable joins result in invalid SQL	Erin Kelly	nobody	"Using the following set of models:

{{{
from django.db import models

class A(models.Model):
    value = models.IntegerField(null=True)

class B(models.Model):
    a = models.ForeignKey(A)

class C(models.Model):
    b = models.ForeignKey(B, null=True)
}}}

The query {{{C.objects.filter(~Q(b__a__value=42))}}} fails with the following error:

{{{DatabaseError: no such column: testapp_b.value}}}

The SQL generated is:

{{{
SELECT ""testapp_c"".""id"", ""testapp_c"".""b_id"" FROM ""testapp_c"" LEFT OUTER JOIN ""t
estapp_b"" ON (""testapp_c"".""b_id"" = ""testapp_b"".""id"") LEFT OUTER JOIN ""testapp_a""
 ON (""testapp_b"".""a_id"" = ""testapp_a"".""id"") WHERE NOT ((""testapp_a"".""value"" = 42
  AND NOT (""testapp_b"".""id"" IS NULL) AND ""testapp_b"".""value"" IS NOT NULL))
}}}

The problem is caused by the last WHERE condition, which is incorrectly filtering on the ""value"" column in the testapp_b table (where it does not exist) instead of in the testapp_a table."	Bug	closed	Database layer (models, ORM)	dev	Normal	fixed	Q ForeignKey nullable		Ready for checkin	1	0	0	0	0	0
