2016-07-25 6 views
1

Ich habe ein Django-Modell wie folgt aus:anpassen Django Rest Framework Serialisierer ausgeben?

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') 

Und Serializer wie folgt aus:

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 

Wenn die RiskActionPerSectionSerializer über einen Blick zugreife, erhalte ich die folgende Ausgabe:

[ 
{ 
    "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" 
} 
..... 
] 

Es ist in Ordnung, aber ich würde das lieber haben:

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

Wie kann ich das mit Django Rest Framework machen?

Antwort

2

Sie to_representation() Methode Ihrer Serializer außer Kraft setzen könnte:

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

Danke, funktioniert perfekt. – user659154

+0

@ user659154 Ihre willkommen –

+0

Wie kann ich die Ausgabestruktur ändern, wie dies mehr zu sein: [ "section1": { "Aktionen": [], "Risiken": [] }, "section2": { "Aktionen": [], "Risiken": [] }, ] – user659154