Opened 8 months ago

Last modified 8 months ago

#35309 closed Cleanup/optimization

Remove Order by on models when prefetching by id — at Initial Version

Reported by: Laurent Lyaudet Owned by: nobody
Component: Database layer (models, ORM) Version: 5.0
Severity: Normal Keywords: prefetch single-valued order_by
Cc: Laurent Lyaudet, Simon Charette Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hello,

I don't know if the "bug" is still here with Django 5.
But on my version of Django, I have the following "bug" :
Assume you have the following code :

class A(models.Model):
    name = models.CharField(max_length=200)

    class Meta:
        ordering = ["name"]


class B(models.Model):
    a = models.ForeignKey(A, related_name="bs", on_delete=models.CASCADE)


a1 = A.objects.create(name="a1")
a2 = A.objects.create(name="a2")
a3 = A.objects.create(name="a3")
a4 = A.objects.create(name="a4")
a5 = A.objects.create(name="a5")
a6 = A.objects.create(name="a6")
a7 = A.objects.create(name="a7")

b1 = B.objects.create(a=a1)
b2 = B.objects.create(a=a2)
b3 = B.objects.create(a=a3)
b4 = B.objects.create(a=a4)
b5 = B.objects.create(a=a5)
b6 = B.objects.create(a=a6)
b7 = B.objects.create(a=a7)

bs = B.objects.all().prefetch_related("a")

The prefetch of as will use the order by and add useless charge on the DB server.
There may be other cases than ForeignKey where the order by is useless.
But since OneToOne inherits from ForeignKey, I don't see anything else right now.

Hence, I request this enhancement, please :)
#ClimateChangeBrake

Best regards,

Laurent Lyaudet

Change History (0)

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