Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I'm new to DRF and have just started building an API. I have two models, a child model connected to a parent model with a foreign key. Here is the simplified version of the model I have:

class Parent(models.Model):     name = models.CharField(max_length=50)   class Child(models.Model):     parent = models.ForeignKey(Parent)     child_name = models.CharField(max_length=80) 

To create serializers, I followed the DRF Serializer Relations and I've created them as the following:

class ChildSerializer(serializers.HyperlinkedModelSerializer):      parent_id = serializers.PrimaryKeyRelatedField(queryset=Parent.objects.all(),source='parent.id')      class Meta:         model = Child         fields = ('url','id','child_name','parent_id')      def create(self, validated_data):         subject = Child.objects.create(parent=validated_data['parent']['id'], child_name=validated_data['child_name'])          return child   class ParentSerializer(serializers.HyperlinkedModelSerializer):     children = ChildSerializer(many=True, read_only=True)     class Meta:         model = Course         fields = ('url','id','name','children') 

I'm trying to get the list of all children in parent's serializer. What I want is to be able to get a response like this:

{     'url': 'https://dummyapidomain.com/parents/1/',       'id': '1',     'name': 'Dummy Parent Name',     'cildren': [         {'id': 1, 'child_name': 'Dummy Children I'},         {'id': 2, 'child_name': 'Dummy Children II'},         {'id': 3, 'child_name': 'Dummy Children III'},         ...     ], } 

I wasn't expecting this to work since there is no link between Parent and Child in the Parent model, but it is the suggested way to do it in the documentation, and it didn't work.

I'm getting the following error message:

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

I think it's perfectly reasonable, but I couldn't understand what I'm missing here.

How can I get the list of all children in parent's serializer?

like image 318
hnroot Avatar asked Nov 22 '15 09:11

hnroot


People also ask

How do you get the context of a serializer?

To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self. context.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What does serializer data return?

Serializer. data returns a copy of the validated data · Issue #5998 · encode/django-rest-framework · GitHub.

What is serializer Is_valid?

is_valid perform validation of input data and confirm that this data contain all required fields and all fields have correct types. If validation process succeded is_valid set validated_data dictionary which is used for creation or updating data in DB.


1 Answers

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

like image 145
AlvaroAV Avatar answered Oct 28 '22 23:10

AlvaroAV