代码之家  ›  专栏  ›  技术社区  ›  Roma

Django REST框架:JSON响应显示ForeignKey值一次(停止重复)

  •  0
  • Roma  · 技术社区  · 6 年前

    我当前的响应列出了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)
    

    但这并没有像我预期的那样起作用,因为它只对单个列表起作用。因此,这适用于详细信息,但不适用于列表类型。

    1 回复  |  直到 6 年前
        1
  •  1
  •   zaphod100.10    6 年前

    不要编辑序列化程序类,而是必须重写 get_paginated_response 方法。

    例如:

    def get_paginated_response(self, data):
        response = super().get_paginated_response(data)
        # insert any custom data you want
        conversation = # code to get conversation
        response.data['conversation_id'] = conversation.id
        owner = #code to get owner object
        response.data['owner'] = owner
        return response
    

    PS:您的“I want to retun”json不正确。