Skip to content

Commit 8b881ec

Browse files
committed
Add opponent to both direct chat serializers
1 parent 46cac60 commit 8b881ec

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

chats/serializers.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ class DirectChatListSerializer(serializers.ModelSerializer):
1414
last_message = serializers.SerializerMethodField()
1515
opponent = serializers.SerializerMethodField()
1616

17-
def get_opponent(self):
17+
def get_opponent(self, chat: DirectChat):
1818
user = self.context.get("opponent")
1919
return UserDetailSerializer(user).data
2020

@@ -32,17 +32,17 @@ class Meta:
3232

3333

3434
class DirectChatDetailSerializer(serializers.ModelSerializer):
35-
users = serializers.SerializerMethodField(read_only=True)
35+
opponent = serializers.SerializerMethodField()
3636

37-
@classmethod
38-
def get_users(cls, chat: DirectChat):
39-
return UserListSerializer(chat.get_users(), many=True).data
37+
def get_opponent(self, chat: DirectChat):
38+
user = self.context.get("opponent")
39+
return UserDetailSerializer(user).data
4040

4141
class Meta:
4242
model = DirectChat
4343
fields = [
4444
"id",
45-
"users",
45+
"opponent",
4646
]
4747

4848

chats/views.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,31 @@ def get_queryset(self):
3636
user = self.request.user
3737
return user.direct_chats.all()
3838

39+
def get(self, request, *args, **kwargs):
40+
chats = self.get_queryset()
41+
serialized_chats = []
42+
for chat in chats:
43+
# fixme: move to function like get_user() and get_opponent()
44+
chat_id = chat.id
45+
user1_id, user2_id = map(int, chat_id.split("_"))
46+
47+
try:
48+
user1 = User.objects.get(pk=user1_id)
49+
user2 = User.objects.get(pk=user2_id)
50+
except User.DoesNotExist:
51+
# fixme: show deleted profile
52+
continue
53+
54+
if user1 == request.user:
55+
opponent = user2
56+
else: # fixme: if user1 == user2
57+
opponent = user1
58+
59+
context = {"opponent": opponent}
60+
serialized_chat = DirectChatListSerializer(chat, context=context).data
61+
serialized_chats.append(serialized_chat)
62+
return Response(serialized_chats, status=status.HTTP_200_OK)
63+
3964

4065
class ProjectChatList(ListAPIView):
4166
serializer_class = ProjectChatListSerializer
@@ -72,8 +97,6 @@ def get(self, request, *args, **kwargs) -> Response:
7297

7398
if user1 == request.user:
7499
opponent = user2
75-
# may be is better to use serializer or return dict -
76-
# {"first_name": user2.first_name, "last_name": user2.last_name}
77100
else:
78101
opponent = user1
79102
context = {"opponent": opponent}

0 commit comments

Comments
 (0)