2016-07-25 57 views
1

我有一個Django模型是這樣的:自定義Django Rest框架序列化器的輸出?

class Sections(models.Model): 
    section_id = models.CharField(max_length=127, null=True, blank=True) 
    title = models.CharField(max_length=255) 
    description = models.TextField(null=True, blank=True) 

class Risk(models.Model): 
    title = models.CharField(max_length=256, null=False, blank=False) 
    section = models.ForeignKey(Sections, related_name='risks') 

class Actions(models.Model): 
    title = models.CharField(max_length=256, null=False, blank=False) 
    section = models.ForeignKey(Sections, related_name='actions') 

而串行這樣的:

class RiskSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Risk 
     fields = ('id', 'title',) 

class ActionsSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Actions 
     fields = ('id', 'title',) 

class RiskActionPerSectionsSerializer(serializers.ModelSerializer): 
    risks = RiskSerializer(many=True, read_only=True) 
    actions = ActionsSerializer(many=True, read_only=True) 

    class Meta: 
     model = Sections 
     fields = ('section_id', 'risks', 'actions') 
     depth = 1 

當通過視圖訪問RiskActionPerSectionSerializer,我得到下面的輸出:

[ 
{ 
    "actions": [ 
     { 
      "id": 2, 
      "title": "Actions 2" 
     }, 
     { 
      "id": 1, 
      "title": "Actions 1" 
     } 
    ], 
    "risks": [ 
     { 
      "id": 2, 
      "title": "Risk 2" 
     }, 
     { 
      "id": 1, 
      "title": "Risk 1" 
     } 
    ], 
    "section_id": "section 1" 
} 
..... 
] 

這很好,但我寧願有:

{ 
"section 1": { 
    "risks": [ 
     { 
      "id": 2, 
      "title": "Risk 2" 
     }, 
     { 
      "id": 1, 
      "title": "Risk 1" 
     } 
    ], 
    "actions": [ 
     { 
      "id": 2, 
      "title": "Actions 2" 
     }, 
     { 
      "id": 1, 
      "title": "Actions 1" 
     } 
    ] 
} 
} 

我該如何使用Django Rest Framework來做到這一點?

回答

2

您可以覆蓋你的串行的to_representation()方法:

class RiskActionPerSectionsSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = Sections 
     fields = ('section_id', 'risks', 'actions') 
     depth = 1 

    def to_representation(self, instance): 
     response_dict = dict() 
     response_dict[instance.section_id] = { 
      'actions': ActionsSerializer(instance.actions.all(), many=True).data, 
      'risks': RiskSerializer(instance.risks.all(), many=True).data 
     } 
     return response_dict 
+0

謝謝,完美的作品。 – user659154

+0

@ user659154的歡迎 –

+0

我怎樣才能改變輸出結構更是這樣的: [ 「SECTION1」:{ 「行動」:[], 「風險」:[] }, 「第2節」: { 「actions」:[], 「risks」:[] }, ] – user659154

相關問題