I've been install Django-Postman user to user messaging package. I'm trying to get user's last message with Rest API.
You can check django-postman package on here: https://pypi.org/project/django-postman/
A part of models.py
class Message(models.Model):""" A message between a User and another User or an AnonymousUser.""" SUBJECT_MAX_LENGTH = 120 subject = models.CharField(_("subject"), max_length=SUBJECT_MAX_LENGTH) body = models.TextField(_("body"), blank=True) sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sent_messages', null=True, blank=True, verbose_name=_("sender")) recipient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='received_messages', null=True, blank=True, verbose_name=_("recipient")) sent_at = models.DateTimeField(_("sent at"), default=now) objects = MessageManager()
Views.py
class InboxLastMessagesViewSet(viewsets.ModelViewSet): serializer_class = InboxLastMessagesSerializer authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Message.objects.filter(Q(sender=user) | Q(recipient=user)).order_by('sender')
Serializers.py
class InboxLastMessagesSerializer(serializers.ModelSerializer): senderusername = serializers.CharField(source='sender.username', read_only=True) reciusername = serializers.CharField(source='recipient.username', read_only=True) sonmesaj = serializers.SerializerMethodField() def get_lastmessage(self, obj): /// I'M TRYING TO CREATE A FUNCTION ON HERE FOR GET SENDER'S LAST MESSAGE //// lastmsg = obj.latest('sent_at') return dict(body=lastmsg) class Meta: model = Message fields = ('senderusername', 'reciusername', 'body', 'sent_at', 'lastmessage')
I want to an output like this:
{"senderusername": "user","reciusername": "user2","body": "Actually that is not last message","sent_at": "2019-01-19T23:08:54Z","lastmessage": {"body": "That's conversation's last message!" } }, {"senderusername": "user","reciusername": "user2","body": "I said that is not last message","sent_at": "2021-05-10T23:09:42Z","lastmessage": {"body": "That's conversation's last message!" } },