Answer the question
In order to leave comments, you need to log in
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)
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
{% for chat in body_chat %}
<h7>Вы: {{ chat.message.0.content }}</h7>
{% endfor %}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question