我想获得用户的聊天列表(字段是:聊天id,聊天参与者),但我不希望用户本身被列在聊天参与者中(我的意思是,用户肯定必须是聊天参与者,但当用户请求他的聊天列表时,没有必要看到他自己的名字列在其他姓名中,因为这是没有意义的)。
下面是聊天模型:
class Chat(models.Model):
id = models.CharField(_('id'), primary_key=True, default=hex_uuid, editable=False, max_length=32)
chat_participants = models.ManyToManyField(User, blank=True)
class Meta:
db_table = 'chat'
verbose_name_plural = 'chats'这是聊天序列化程序:
class ChatSerializer(serializers.ModelSerializer):
chat_participants = ChatParticipantsSerializer(many=True, read_only=True)
class Meta:
model = Chat
fields = '__all__'PS ChatParticipantsSerializer (它的模型是User)用于获取参与者的姓名,而不仅仅是他们的id。
视图如下所示:
class ChatsListAPIView(generics.ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = ChatSerializer
def get_queryset(self):
return Chat.objects.filter(chat_participants=self.request.user.id)PS in get_queryset函数我检查用户是否在聊天组中(如果他是组中的聊天参与者)
现在,我在JSON中获得了以下内容:
[
{
"id": "a38609b1c86f4d71b0b300381db747b4",
"chat_participants": [
{
"id": "044ad4f8876d4b8bb057a63769a33027",
"first_name": "Jean",
"last_name": "Mel"
},
{
"id": "c01473b5d72a4b0ea40a4047ed297d77",
"first_name": "Sasha",
"last_name": "King"
}
]
},
{
"id": "4fdf4a34eaf6464baf55b08676b7d6a6",
"chat_participants": [
{
"id": "c01473b5d72a4b0ea40a4047ed297d77",
"first_name": "Sasha",
"last_name": "King"
},
{
"id": "ffcf4d06958b4926bee833166279f0c6",
"first_name": "Anne",
"last_name": "Brown"
}
]
}
]这是我的JSON格式的聊天列表。所以我得到了聊天的in,以及聊天中的所有参与者(这里只有两个参与者)。如果我是Sasha King,我如何从JSON中的聊天参与者中删除这个名称,因为向自己显示用户的名称是没有意义的(不知道,也许是在序列化程序本身中编写一个不包含self.request.user的函数……)
我想要得到这个:
[
{
"id": "a38609b1c86f4d71b0b300381db747b4",
"chat_participants": [
{
"id": "044ad4f8876d4b8bb057a63769a33027",
"first_name": "Jean",
"last_name": "Mel"
}
]
},
{
"id": "4fdf4a34eaf6464baf55b08676b7d6a6",
"chat_participants": [
{
"id": "ffcf4d06958b4926bee833166279f0c6",
"first_name": "Anne",
"last_name": "Brown"
}
]
}
]发布于 2021-01-29 20:59:50
我还没有测试代码,但是这个想法应该行得通。基本上,你过滤参与者,然后“手动”序列化他们。
class ChatSerializer(serializers.ModelSerializer):
chat_participants = SerializerMethod()
class Meta:
model = Chat
fields = '__all__'
def get_chat_participants(self, obj):
return ChatParticipantsSerializer(obj.chat_participants.exclude(self.context["request"].user) many=True, read_only=True).datahttps://stackoverflow.com/questions/65941425
复制相似问题