﻿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
35309	Elide ordering of prefetch querysets for single valued relationships	Laurent Lyaudet	Laurent Lyaudet	"While the ordering of multi-valued relationships must be preserved when prefetching relationships is it unnecessary when using `prefetch_related` against single valued relationships.

For example, given the following models

{{{#!python
class Author(models.Model):
    name = models.CharField(max_length=200)

    class Meta:
        ordering = [""name""]


class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, related_name=""books"", on_delete=models.CASCADE)

    class Meta:
        ordering = [""title""]
}}}

The ordering of an author's books in `Author.objects.prefetch_related(""books"")` has a significance as multiple books might be associated with each authors.

It's not the case for a book's author in `Book.objects.prefetch_related(""author"")` through as the relationship can only contain a single author and there is a single way to order the members of a singleton.

In other words `sorted([element], key=sort_func)` will result in `[element]` for any `sort_func`.

This property holds true for all the single valued relationships that the ORM supports (backward and forward 1:1 and forward 1:M) which allows the prefetching to elide any predefined ordering safely to avoid an unnecessary and possibly expensive ordering defined for the related model queryset.
Currently the prefetch of authors will use the order by and add useless load on the DB server.
It would be useful to remove this order by.
#ClimateChangeBrake

"	Cleanup/optimization	assigned	Database layer (models, ORM)	5.0	Normal		prefetch single-valued order_by	Laurent Lyaudet Simon Charette	Accepted	1	0	0	1	0	0
