Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested Serializer Not Working in django rest framework. How can I fix it?

Can you tell me where is the actual problem?
My goal is to build up an API that will show how many courses an instructor offers.

models.py:

class Instructor(models.Model):
    name = models.CharField(max_length=40)
    email = models.CharField(max_length=250)


class Course(models.Model):
    Title = models.CharField(max_length=250)
    Instructor = models.ForeignKey(Instructor, on_delete=models.CASCADE, related_name="CourseInstructorRelatedNAme")

Serializer.py:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class CourseSerializer(ModelSerializer):
    class Meta:
        model = Course
        fields = '__all__'

class InstructorSerializer(ModelSerializer):

    courses = CourseSerializer(many=True, read_only=True)
    class Meta:
        model = Instructor
        fields = '__all__'

views.py:

class CourseViewSet(ModelViewSet):
    serializer_class = CourseSerializer
    queryset = Course.objects.all()

class InstructorViewSet(ModelViewSet):
    serializer_class = InstructorSerializer
    queryset = Instructor.objects.all()

urls.py:

router.register(r"course", views.CourseViewSet , basename="course")
router.register(r"instructor", views.InstructorViewSet , basename="instructor")

>Solution :

The related_name is the name you of the reverse relation you have to use if you want to access the items from the parent object.

If you want to retrieve your queryset of courses as courses, you need to change the related_name in your model:

# models.py
class Course(models.Model):
    Title = models.CharField(max_length=250)
    Instructor = models.ForeignKey(Instructor, on_delete=models.CASCADE, related_name="courses")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading