I have following models:
class Topic(models.Model):
title = models.CharField(max_lenght=32)
# Some other fields.
class Thread(models.Model):
topic = models.ForeignKey(Topic, related_name=threads', on_delete=models.CASCADE)
# some other fields
class Message(models.Model):
thread = models.ForeignKey(Thread, related_name='messages', on_delete=models.CASCADE)
text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
I want to calculate index of each element in each Thread
, in the queryset by F()
. For example If in the Thread 1
I have 5 messages, I want to messages have indexes as 1 to 5.
my code doesn't work.
code comes in the following:
from django.models import Count, Q, F
messages = Message.objects.filter(...).annotate(
index=Count('id', filter=Q(thread_id=F('thread_id'), created__lt=F('created'))) + 1
).annotate(
page=F('index') / 20
)
This return same index for all elements. For example this returns index=5 for all items in queryset.
How can I calculate index of elements in the queryset?
UPDATE:
Consider following:
I have 1000 Messages.
page size = 20.
number of messages pages = 1000 / 20 = 50
Now if I filter searched = Message.objects.filter(text__contains="hello")
, 5 messages will be returned in the searched
queryset.
My ultimate goal is to find each message is in which page? (I have 50 pages)