﻿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
2884	[newforms-admin] Incorrect sql generated when ordering a queryset where the related model's Meta.ordering has an FK	bangcok_dangerus ( at ] hotmail.com	nobody	"'''Description:''' In the admin, clicking to sort on a field specified in list_display causes a !ProgrammingError due to a non-existent column in the SQL ORDER BY clause.

'''How to replicate:''' This happens when the field specified in list_display is a !ForeignKey to another object, and this related object contains a Meta ordering option which is also a !ForeignKey. Example minimal models.py:


{{{
from django.db import models

class Subject(models.Model):
	name = models.CharField(maxlength=40)
	def __str__(self):
		return self.name
	class Admin:
		pass

class Course(models.Model):
	name = models.CharField(maxlength=40)
	subject = models.ForeignKey(Subject)
	def __str__(self):
		return self.name
	class Admin:
		list_display = ('__str__', 'subject')
	class Meta:
		ordering = [""subject""]

class Class(models.Model):
	course = models.ForeignKey(Course)
	name = models.CharField(maxlength = 40)
	def __str__(self):
		return self.name
	class Admin:
		list_display = ('__str__','course')
	class Meta:
		verbose_name_plural = ""Classes""
}}}

Navigating to the Classes page and clicking on the 'course' column to order will generate the error.

'''Cause:''' This is a bug in django/contrib/admin/views/main.py . The code in !ChangeList.get_query_set wrongly assumes that the ordering option in the related object is a field in the related object's table. For the above model, the incorrect ORDER BY clause currently generated is 'test_course.subject'.

'''Fix:''' This patch recursively follows any !ForeignKeys in the ordering options to find the correct ORDER BY clause, in this case 'test_subject.name'. In the case of circular !ForeignKeys with circular ordering, it will order by the related object's raw !ForeignKey field (e.g. course.subject_id)

-Basil
"	defect	closed	contrib.admin	dev	normal	fixed		real.human@…	Accepted	1	0	0	1	0	0
