G
G
gromyko212020-10-07 14:02:27
Django
gromyko21, 2020-10-07 14:02:27

Sorting foreign_key objects?

I'm trying to sort chats by the latest message (last message at the top of the list).
Model

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


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)

view
body_chat = body_chat.order_by('-received_messages__pk')

    for chat in body_chat:
        chat_id = get_object_or_404(Chat, id=chat.id)
        message = Message.objects.order_by('-pk').filter(recipient=chat_id)[0:1]
        chat.message = message

Sample
{% for chat in body_chat %}
        <h7>Вы: {{ chat.message.0.content }}</h7>
{% endfor %}

With this sorting, for each message sent, the template creates a new chat. But if you do sorting, for example, like this: body_chat = Chat.objects.filter(members=request.user).order_by('-pk') then it doesn't create anything extra, but sorting goes accordingly by pk.
How can be eliminated?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question