Answer the question
In order to leave comments, you need to log in
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
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)
class ThreadSerializer(serializers.ModelSerializer):
participants = UserWrap(many=True)
class Meta:
model = Thread
fields = ('id','get_last_message', 'participants')
[
{
"id": 1,
"get_last_message": "Hi",
"participants": [
{
"id": 1,
"username": "test",
"pic": "/media/I45TU27WKS8U.png"
},
{
"id": 2,
"username": "Just",
"pic": "/media/EUHT4ZC5ZE6R.png"
}
]
},
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