﻿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
16781	Wrong SQL for a query-set	German M. Bravo	nobody	"I'm using Django 1.3 and the postgres (postgresql_psycopg2) backend. A query set is producing the wrong (invalid) SQL.

Query that breaks the SQL:
`Address.objects.exclude(user__relationships_from__from_user__id=100)`
Resulting in:
{{{
#!div style=""font-size: 80%""
Code highlighting:
  {{{#!sql
SELECT ""bug3_address"".""id"", ""bug3_address"".""user_id"", ""bug3_address"".""address"" FROM ""bug3_address"" WHERE NOT (""bug3_address"".""user_id"" IN (SELECT U2.""from_user_id"" FROM ""entities_user"" U1 WHERE (U0.""user_id"" = 100  AND U2.""from_user_id"" IS NOT NULL)))
  }}}
}}}

However, this works fine:
`Address.objects.exclude(user__relationships_to__from_user__id=100)`
Resulting in:
{{{
#!div style=""font-size: 80%""
Code highlighting:
  {{{#!sql
SELECT ""bug3_address"".""id"", ""bug3_address"".""user_id"", ""bug3_address"".""address"" FROM ""bug3_address"" WHERE NOT ((""bug3_address"".""user_id"" IN (SELECT U2.""to_user_id"" FROM ""bug3_relationship"" U2 WHERE (U2.""from_user_id"" = 100  AND U2.""to_user_id"" IS NOT NULL)) AND ""bug3_address"".""user_id"" IS NOT NULL))
  }}}
}}}


Also accessing other attributes works fine:
`Address.objects.exclude(user__relationships_from__status='A')`
Resulting in:
{{{
#!div style=""font-size: 80%""
Code highlighting:
  {{{#!sql
SELECT ""bug3_address"".""id"", ""bug3_address"".""user_id"", ""bug3_address"".""address"" FROM ""bug3_address"" WHERE NOT ((""bug3_address"".""user_id"" IN (SELECT U2.""from_user_id"" FROM ""bug3_relationship"" U2 WHERE (U2.""status"" = A  AND U2.""from_user_id"" IS NOT NULL)) AND ""bug3_address"".""user_id"" IS NOT NULL))
  }}}
}}}


These are the models:
{{{
#!div style=""font-size: 80%""
Code highlighting:
  {{{#!python

from django.db import models
from django.contrib.auth.models import User

class Address(models.Model):
    user = models.ForeignKey(User)
    address = models.CharField(max_length=100)

class Relationship(models.Model):
    status = models.CharField(max_length=1)
    from_user = models.ForeignKey(User, related_name='relationships_from')
    to_user = models.ForeignKey(User, related_name='relationships_to')
  }}}
}}}"	Bug	closed	Database layer (models, ORM)	1.3	Normal	fixed		German M. Bravo	Accepted	0	0	0	0	0	0
