I am trying to make an API that is series.
The app is really very simple. It has Series, Seasons and Episodes.
I leave the models of each one so you can see:
model series:
class Serie(SeriesAPIModel):
"""Serie model."""
title = models.CharField('Series title', max_length=250)
release = models.DateField('Release date', default=timezone.now())
description = models.TextField('Series description', blank=True, null=True)
image = models.ImageField('Series image', upload_to='series/images/')
def __str__(self):
"""Return series title."""
return self.title
seasons model:
class Season(SeriesAPIModel):
"""Season model."""
title = models.CharField('Season title', max_length=250)
serie = models.ForeignKey(Serie, on_delete=models.CASCADE)
def __str__(self):
"""Return season title and serie."""
return f'{self.serie}: {self.title}'
episode models:
class Episode(SeriesAPIModel):
"""Episode model."""
title = models.CharField('Episode title', max_length=250)
video = models.URLField()
image = models.ImageField('Episode image', upload_to='episodes/images/')
season = models.ForeignKey(Season, on_delete=models.CASCADE)
def __str__(self):
"""Return episode title, season title and serie."""
return f'{self.season.serie}: {self.season}: {self.title}'
I want that when doing a GET of the series the seasons come out, and also that when listing the seasons the episodes come out.
What I did now was this, although it didn't work:
serializer.py
class SerieModelSerializer(serializers.ModelSerializer):
"""Serie model serializer."""
seasons = serializers.StringRelatedField(many=True)
class Meta:
"""Meta class."""
model = Serie
fields = '__all__'
class SeasonModelSerializer(serializers.ModelSerializer):
"""Season model serializer."""
episodes = serializers.StringRelatedField(many=True)
class Meta:
"""Meta class."""
model = Season
fields = '__all__'
class EpisodeModelSerializer(serializers.ModelSerializer):
"""Episode model serializer."""
class Meta:
"""Meta class."""
model = Episode
fields = '__all__'
I hope you can help me, thank you very much!
You could modify your models by adding
related_name
toForeignKey
to allow an inverse relationship (note that for simplicity I removed some properties from the models)Later, in the serializers, you have to use the serializers of each model (note that for this, the order in which they are written is important) and in the fields, you have to use the
related_name
ones that were added.Finally, my views (I only created a quick test template. Surely you have it implemented differently)