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)
Source:stackexchange.com