﻿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
33678	order_by crash when sorting by a foreign key referencing a Model with an ordering that includes expressions	Eduardo Rivas	nobody	"Possibly related to https://code.djangoproject.com/ticket/31481

{{{
# models.py
from django.db import models
from django.db.models.functions import Lower


class Material(models.Model):
    code = models.CharField(max_length=255, unique=True)

    class Meta:
        ordering = (Lower(""code""),)

    def __str__(self):
        return self.code


class QuotePartMaterial(models.Model):
    material = models.ForeignKey(Material, on_delete=models.PROTECT)

    def __str__(self):
        return str(self.material)
}}}


{{{
# admin.py
from django.contrib import admin
from . import models


admin.site.register(models.Material)


@admin.register(models.QuotePartMaterial)
class QuotePartMaterialAdmin(admin.ModelAdmin):
    list_display = (""material"",)
}}}

Loading the admin works fine, but If I try to manually sort QuotePartMaterial records in the admin by clicking the ""Material"" column header, I get:

{{{
FieldError at /admin/example/quotepartmaterial/
Cannot resolve keyword 'code' into field. Choices are: id, material, material_id
}}}

Removing the Lower() call on Material.Meta.ordering makes the issue go away.
"	Bug	closed	Database layer (models, ORM)	4.0	Normal	duplicate			Accepted	0	0	0	0	0	0
