F
F
FulTupFul2018-07-26 13:12:34
Django
FulTupFul, 2018-07-26 13:12:34

How to display the recipient's name in a chat?

I use django and drf

class Thread(models.Model):
    participants = models.ManyToManyField(User)
    last_message = models.DateTimeField(null=True, blank=True, db_index=True)
    is_chat = models.BooleanField('Чат', default=True)
    is_group = models.BooleanField('Группа', default=False)

    def get_last_message(self):
        try:
            return self.message_set.latest('id').text
        except:
            return ""


class Message(models.Model):
    text = models.TextField()
    sender = models.ForeignKey(User, on_delete=models.CASCADE)
    thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
    datetime = models.DateTimeField(auto_now_add=True, db_index=True)

    def __str__(self):
        return self.text

Here is such a twist:
class Threads(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, format=None):
        queryset = User.objects.get(username=request.user).thread_set.all()
        serializer = ThreadSerializer(queryset, many=True)
        return Response(serializer.data)

And here's a serializer:
class ThreadSerializer(serializers.ModelSerializer):

    participants = UserWrap(many=True)
    class Meta:
        model = Thread
        fields = ('id','get_last_message', 'participants')

It turns out something like this api:
[
    {
        "id": 1,
        "get_last_message": "Hi",
        "participants": [
            {
                "id": 1,
                "username": "test",
                "pic": "/media/I45TU27WKS8U.png"
            },
            {
                "id": 2,
                "username": "Just",
                "pic": "/media/EUHT4ZC5ZE6R.png"
            }
        ]
    },

How to display only the recipient's data in participants? I thought through passing the second request using exclude (), but this is impossible.

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