Reputation: 2402
I'm new to django, and I want to select last message of each thread:
models.py
class ChatMessage(models.Model):
thread = models.ForeignKey('Thread', null=True, blank=True, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="sender", on_delete=models.CASCADE)
message = models.TextField(null=True)
timestamp = models.DateTimeField(auto_now_add=True)
voice = models.FileField(upload_to=upload_voice_dir, blank=True, null=True)
I'v no idea how to filter(I just know basics of filtering). to sum it up I want the last message of each thread.
Upvotes: 0
Views: 339
Reputation: 51988
You can use Subquery expression here. For example:
from django.db.models import OuterRef, Subquery
newest = ChatMessage.objects.filter(thread=OuterRef('pk')).order_by('-timestamp')
query = Thread.objects.annotate(newest_msg=Subquery(newest.values('message')[:1])).values('pk','newest_msg')
Upvotes: 1
Reputation: 5746
There may be a better way to handle this. However you can create a list of distinct ForeignKeys
using values_list
and distinct()
and then loop over your list to pull the last()
row entered in the database for that thread.
keys = ChatMessage.objects.values_list('thread', flat=True).distinct()
for key in keys:
last_message = ChatMessage.objects.filter(thread_id=key).last()
Upvotes: 1