G
G
gromyko212020-10-02 09:21:17
Django
gromyko21, 2020-10-02 09:21:17

How to sort parent objects by children?

There are 2 models:

class Chat(models.Model):
    members = models.ManyToManyField(User, verbose_name="Участник", related_name='members')


class Message(models.Model):
    author = models.ForeignKey(User, verbose_name="Отправитель", on_delete=models.CASCADE)
    recipient = models.ForeignKey(Chat, related_name='received_messages', verbose_name="Получатель", 
on_delete=models.CASCADE)

Message is bound to chat. And I need to sort the chat under the latest message.
Right now my sorting works by chat creation time
messages = Chat.objects.order_by('-pk').filter(members=request.user)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
reqww, 2020-10-02
@gromyko21

Add the time of sending to the message,
and as a result, the sorting will be like this:
Chat.objects.order_by('received_messages__timestamp')
If timestamp is a field in the Message of type models.DateTimeField
PS A minus at the beginning is possible

D
Dr. Bacon, 2020-10-02
@bacon

1. add the time of the last message via annotate https://docs.djangoproject.com/en/3.1/ref/models/q... and sort by it
2. Chat must have members, not Message? And then so in each message the list of participants is duplicated

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question