1

I have a Django model like this:

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

And serializers like that :

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

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

When accessing the RiskActionPerSectionSerializer over a view, I get the following output:

[
{
    "section 1": {
        "risks": [],
        "actions": []
    }
},
{
    "section 2": {
        "risks": [],
        "actions": []
    }
},
.....
]

It s fine but I would prefer to have that :

[

    "section 1": {
        "risks": [],
        "actions": []
    },
    "section 2": {
        "risks": [],
        "actions": []
    }
.....
]

Also why is it returning an array by default [] and not an object for example like:

{
 "count": 0,
 "next": null,
 "previous": null,
 "results": []
 }

3 Answers 3

2

You need to override the to_representation() method of your serializer class. It is mention in brief in this official documentation link: http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior

Other option is overriding the get and post methods of your class APIView or it's inherited class

Sign up to request clarification or add additional context in comments.

Comments

0

You can't store key/value pairs in list, ['key': {}] won't work, you should access to item by index instead, like in your representation.
Array returned because of many=True which means you put many objects in serializer and it wait sequence from you.

Comments

0

I can't see the ORM query that resulted in this output, but Your query is returning multiple items that match your criteria. Default behaviour of any frameworks, let alone DRF, is to put them inside an array and return them as an "Array of objects" as in your result.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.