1

I'm fighting to find my way into DRF and can't get related data into my endpoint.

models.py

class ChapterMark(models.Model):
    title           = models.CharField(max_length=100, null=True)
    episode         = models.ForeignKey(Episode, on_delete=models.CASCADE)
    start_time      = models.CharField(max_length=20)


class Episode(models.Model):
    title           = models.CharField(max_length=100, blank=False)
    show            = models.ForeignKey(Show, on_delete=models.PROTECT)

serializers.py

class ChapterMarkSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChapterMark
        exclude = ('')

class EpisodeSerializer(serializers.ModelSerializer):
    chapters = ChapterMarkSerializer(source='id')

    class Meta:
        model = Episode
        depth = 1

The error I'm getting is

Got AttributeError when attempting to get a value for field start_time on serializer ChapterMarkSerializer. The serializer field might be named incorrectly and not match any attribute or key on the int instance. Original exception text was: 'int' object has no attribute 'start_time'.

My guess is that the relation via source='id' just doesn't work but everything I found so far is pointing back to doing it that way.

There's a many to one relationship between chapters and episodes (so each episode has many chapters). I'm sure I'm just missing an important part.

1 Answer 1

2

To get reverse relation object use chaptermark_set as source of chapters field, also dont forget to add many=True since episode can have miltiple chapters:

class EpisodeSerializer(serializers.ModelSerializer):
    chapters = ChapterMarkSerializer(source='chaptermark_set', many=True)

    class Meta:
        model = Episode
        depth = 1 
Sign up to request clarification or add additional context in comments.

1 Comment

awesome, thanks. I had many=Truein there before but got confused by other errors and took it out. Works now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.