我当前的响应列出了serialiser中的所有字段,如下所示:
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"conversation_id": 1,
"owner": true,
"sender": 2,
"body": "Hello There"
},
{
"conversation_id": 1,
"owner": true,
"sender": 2,
"body": "Second message"
}
]
}
相反,因为
conversation_id
和
owner
都是重复的,我想把他们以外的主要反应。我
想要返回
:
{
"count": 2,
"next": null,
"previous": null,
"results": [
"owner": True,
"conversation_id":1,
"messages": {
{
"sender": 2,
"body": "Hello There"
},
{
"sender": 2,
"body": "Second Message"
},
},
]
}
序列化程序。py公司
class MessageSerializer(serializers.ModelSerializer):
sender = serializers.ReadOnlyField(source='sender.id')
conversation_id = serializers.SerializerMethodField()
owner = serializers.SerializerMethodField()
def get_conversation_id(self, obj):
conversation = Conversation.objects.filter(message=obj)[0]
return conversation.id
def get_owner(self, obj):
owner = #code to get owner object, the person who started the conversation
user = self.context['request'].user
if owner == user:
return True
else:
return False
class Meta:
model = Message
fields = ['conversation_id','sender','body','owner']
我尝试的内容:
我尝试使用创建另一个名为messages的字段
messages = serializers.SerializerMethodField()
并使用以下功能,
def get_messages(self, obj):
return dict(body=obj.body, sender=obj.sender.id)
但这并没有像我预期的那样起作用,因为它只对单个列表起作用。因此,这适用于详细信息,但不适用于列表类型。