Opened 3 years ago

Last modified 2 years ago

#29538 assigned Bug

Query Expression in ordering of a related object fails

Reported by: wilhelmhb Owned by: Alexandre Laplante
Component: Database layer (models, ORM) Version: 2.0
Severity: Normal Keywords: ordering, query expression, related object
Cc: wilhelmhb, colons Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description (last modified by Tim Graham)

Since 2.0, according to the doc (, we can use QueryExpression objects in the Model.Meta.ordering field.

from django.db import models

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100, null=True, blank=True)

    class Meta:
        ordering = [models.F('instrument').asc(nulls_last=True)]

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

    class Meta:
        ordering = ['artist']
>>> Album.objects.all()
TypeError: 'OrderBy' does not support indexing

When reaching, the compiler tries to use the related model, but at line 679, item can be an OrderBy object. Thus the failure.

Change History (6)

comment:1 Changed 3 years ago by wilhelmhb

Cc: wilhelmhb added

comment:2 Changed 3 years ago by Tim Graham

Description: modified (diff)
Summary: QueryExpression in ordering of a related object failsQuery Expression in ordering of a related object fails
Triage Stage: UnreviewedAccepted

comment:3 Changed 3 years ago by Alexandre Laplante

Owner: changed from nobody to Alexandre Laplante
Status: newassigned

Started working on a fix.

comment:4 Changed 3 years ago by Alexandre Laplante

Has patch: set

PR Looking for feedback on this patch.

comment:5 Changed 2 years ago by Carlton Gibson

Patch needs improvement: set

comment:6 Changed 2 years ago by colons

Cc: colons added
Note: See TracTickets for help on using tickets.
Back to Top