Gorbie Chev
Gorbie Chev

Reputation: 53

Displaying nested entities in Django REST Framework

I would like to display nested entities in the Django REST response – not hyperlinked entities or primary keys - the actual entity inside the parent.

This would look something like this:

{ 'id': 5
  'name' : 'blah'
  'children' : [
      {'id' : 77, 'foo' : 'bar'},
      {'id' : 78, 'foo' : 'bar'},
      ...
  ]
}

This is mentioned in the REST documentation as one possible way of representing relationships between entities, but the documentation doesn't indicate how it can be done.

Upvotes: 1

Views: 265

Answers (1)

Evans Murithi
Evans Murithi

Reputation: 3257

The documentation indicates use of nested relationships: DRF Nested relationships

Basically you put the related_name of the child model in the serializer e.g. related_name = ChildSerializer(many=True, read_only=True). The link has a pretty good example.

Upvotes: 1

Related Questions