1+ from django .db .models import Q # Import Q object for building complex queries using OR conditions
12from rest_framework import serializers
23
3- from zserver .models import Session , SignUpOTP , UnverifiedUserProfile , UserProfile , VerifyUserOTP
4+ from zserver .models import (
5+ Message ,
6+ Session ,
7+ SignUpOTP ,
8+ UnverifiedUserProfile ,
9+ UserProfile ,
10+ VerifyUserOTP ,
11+ )
412
513
614# Serializer class for the UserProfile model
715class UserProfileSerializer (serializers .ModelSerializer ):
16+ # Add dynamic field for last message between the user and the contact
17+ last_message = serializers .SerializerMethodField ()
818 class Meta :
919 """Meta class to specify the model and fields to be serialized."""
1020
@@ -14,11 +24,27 @@ class Meta:
1424 "fullname" ,
1525 "email" ,
1626 "password" ,
27+ "last_message" ,
1728 ] # Fields to be included in the serialization
1829 extra_kwargs = {
1930 "password" : {"write_only" : True }, # Make the password field write-only
2031 }
2132
33+ def get_last_message (self , contact : UserProfile ) -> str :
34+ """Retrieve the last message exchanged with the given contact."""
35+ # Get the authenticated user from serializer context
36+ user = self .context .get ("user" )
37+ if not user :
38+ return None
39+
40+ # Fetch the latest message between user and this contact
41+ last_msg = Message .objects .filter (
42+ Q (sender = user , receiver = contact ) | Q (sender = contact , receiver = user ),
43+ ).order_by ("-timestamp" ).first ()
44+
45+ # Return message text if available, else None
46+ return last_msg .content if last_msg else None
47+
2248 def update (self , instance : UserProfile , validated_data : dict ) -> UserProfile :
2349 """Update an existing user profile."""
2450 instance .fullname = validated_data .get ("fullname" , instance .fullname )
0 commit comments