I've tried a few solutions posted elsewhere for this problem but with no luck. It seems like it is not natively supported in DRF. Does anyone have suggestions on how to accomplish this?
I have a reports
model and a section
model. A section is defined as follows:
class Section(models.Model):
title = models.CharField(max_length=255)
report = models.ForeignKey(Report)
order = models.PositiveIntegerField()
section = models.ForeignKey('self', related_name='section_section', blank=True, null=True)
content = models.TextField(blank=True)
I want to have it display data like so under reports:
[
{
"id": 1,
"title": "test",
"subtitle": "test",
"section_set": [
{
"id": 1,
"title": "test",
"report": 1,
"order": 1,
"section_set": [
{
"id": 1,
"title": "test",
"report": 1,
"order": 1,
"section": null,
"content": "<p>test</p>"
},
{
"id": 2,
"title": "test",
"report": 1,
"order": 1,
"section": 2,
"content": "<p>test</p>"
},
{
"id": 3,
"title": "test",
"report": 1,
"order": 1,
"section": null,
"content": "<p>test</p>"
}
],
"content": "<p>test</p>"
},
{
"id": 2,
"title": "test",
"report": 1,
"order": 1,
"section": 2,
"content": "<p>test</p>"
},
{
"id": 3,
"title": "test",
"report": 1,
"order": 1,
"section": null,
"content": "<p>test</p>"
}
]
}
]
My current (attempted) implementation looks like this:
class SubsectionSerializer(serializers.ModelSerializer):
class Meta:
model = Section
class SectionSerializer(serializers.ModelSerializer):
section = SubsectionSerializer()
class Meta:
model = Section
fields = ('id', 'title', 'report', 'order', 'section', 'content')
class CountryReportSerializer(serializers.ModelSerializer):
section_set = SectionSerializer(many=True)
class Meta:
model = CountryReport
fields = ('id', 'title', 'subtitle', 'section_set')
class MapsSerializer(serializers.ModelSerializer):
class Meta:
model = Map
fields = ('id', 'country', 'map_image', 'report')
but the output looks like this:
{
"id": 1,
"title": "test",
"subtitle": "test",
"section_set": [
{
"id": 1,
"title": "Section 1",
"report": 1,
"order": 1,
"section": null,
"content": "<p>test</p>"
},
{
"id": 2,
"title": "Section 2",
"report": 1,
"order": 1,
"section": null,
"content": "<p>test</p>"
},
{
"id": 3,
"title": "Subsection 1",
"report": 1,
"order": 1,
"section": {
"id": 1,
"title": "Section 1",
"order": 1,
"content": "<p>test</p>",
"report": 1,
"section": null
},
"content": "<p>test</p>"
}
]
}