简体   繁体   中英

django queryset to select max id of each distinct filed

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 .

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()

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM