﻿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
24367	ORA-00918 (column ambiguously defined) when using a combination of slicing, distinct, and order_by	skoot	nobody	"The steps to reproduce the problem are fairly simple.

First, you need at least 3 models :
- The first model has foreign keys to the other two
- The other two have a field with a similar name.

Here is a minimalistic example (pseudo-code):

{{{
class A (Model):
  b = ForeignKey(B)
  c = ForeignKey(C)

class B (Model):
  name = CharField()

class C (Model)
  name = CharField()
}}}

So model A has foreign keys to models B and C, and models B and C both have a field called ""name"".

If we then select B's ""name"" field while ordering by C's ""name"" field in a distinct and sliced query, it fails with an ORA-00918 error (column ambiguously defined). In our example, the queryset would look something like this:

{{{
A.objects.values(""b__name"").order_by(""c__name"").distinct()[:10]
or
A.objects.select_related(""b"").order_by(""c__name"").distinct()[:10]
}}}

If you remove either the order_by, the distinct(), or the slicing, it works. If you have all 3, it breaks.

The generated SQL query looks something like this:

{{{
SELECT * FROM (SELECT ROWNUM AS ""_RN"", ""_SUB"".* FROM (SELECT DISTINCT ""B"".""NAME"" AS ""NAME"", ""C"".""NAME"" FROM ""A"" INNER JOIN ""B"" ON ( ""A"".""A_ID"" = ""B"".""A_ID"" ) INNER JOIN ""C"" ON ( ""A"".""C_ID"" = ""C"".""C_ID"" ) ORDER BY ""C"".""NAME"" ASC) ""_SUB"" WHERE ROWNUM <= 10) WHERE ""_RN"" > 0
}}}

I've reproduced the bug both on django 1.4 and on django 1.7, and it is oracle specific (my application works fine on pgsql).
"	Bug	closed	Database layer (models, ORM)	1.7	Normal	fixed	ORA-00918 oracle queryset		Unreviewed	0	0	0	0	0	0
