[Django]-Django Rest Framework Serializer Relations: How to get list of all child objects in parent's serializer?

24๐Ÿ‘

โœ…

I think your problem is you forgot to add a related_name for your Children model. I would have the models like this:

class Parent(models.Model):
    name = models.CharField(max_length=50)

class Child(models.Model):
    parent = models.ForeignKey(Parent, related_name='children')  # <--- Add related_name
    child_name = models.CharField(max_length=80)

And I think with this change you will solve the error your getting

๐Ÿ‘คAlvaroAV

15๐Ÿ‘

You can implement this in two way:

  1. With SerializerMethodField :
    your code became like this:

    class ParentSerializer(serializers.ModelSerializer):
    
         children_list = serializers.SerializerMethodField('_get_children')
    
         def _get_children(self, obj):
             serializer = ChildSerializer(obj.child_list(), many=True)
             return serializer.data
    
        class Meta:
            model = Course
            fields = ('url','id','name','children_list')
    
  2. Every field could be attribute of model or a method, so you can define a get_children_list method in Parent model, then call it in list of fields of ParentSerializer:

    class ParentSerializer(serializers.ModelSerializer):
    
        class Meta:
             model = Course
             fields = ('url','id','name','get_children_list')
    

Note: You need to inherits from serializers.ModelSerializer in this scenario

๐Ÿ‘คMoe Far

Leave a comment