[Answered ]-Django- How to get element index in a queryset by using F expression

1👍

If you want this done by the database, you want to look into Window functions, specifically the Rank function (https://docs.djangoproject.com/en/3.2/ref/models/database-functions/#rank), which allows you to assign each row a number according to a grouping (like by thread)

This might do the trick:

from django.db.models import Window, F
from django.db.models.functions import Rank

index = Window(
    expression=Rank(),
    order_by=F('created'),
    partition_by=F('thread'),
)
Message.objects.annotate(index=index)

Leave a comment