I have the following models:
class Section(models.Model):
name = models.CharField(max_length=255)
class Dataset(models.Model):
name = models.CharField(max_length=255)
sections = models.ManyToManyField(Section)
class File(models.Model):
dataset = models.ForeignKey(Dataset)
section = models.ForeignKey(Section, related_name='files')
key = models.CharField(max_length=255)
Serializers:
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = File
fields = ('id', 'key')
class SectionSerializer(serializers.ModelSerializer):
files = FileSerializer(many=True)
class Meta:
model = Section
fields = ('name', 'files')
class DatasetSerializer(serializers.ModelSerializer):
sections = SectionSerializer(many=True)
class Meta:
model = Dataset
fields = ('id', 'name', 'sections')
And viewset:
class DatasetsViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = DatasetSerializer
queryset = Dataset.objects.prefetch_related(
'sections', 'sections__metric', 'sections__feature', 'sections__files')
I am trying to load the datasets (/api/datasets endpoint) with the list of their sections and for each section the list of files associated to get something like:
[
{
"id": 1,
"name": "Q4 2015",
"sections": [
{
"id": 1,
"name": "Overall Scores"
"files": [
{
"id": 1,
"key": "this/is/a/path"
}
]
}
]
}
]
The tricky part is that the list of files for a given section should be filtered by the parent dataset. Right now the sections contains all the files regardless of their dataset. What would be the best way to do this?
Thanks!