Reputation: 328
Using Django REST JSON Api, i.e. djangorestframework-jsonapi==3.1.0 and having the following data structure: parent, singleChild, manyGrandChildren (all just dummy names, singleChild means one-to-one relation, manyGrandChildren means one-to-many nested relation).
...
class Parent(serializers.HyperlinkedModelSerializer):
included_serializers = {
'singleChild': singleChildSerializer,
'manyGrandChildren': manyGrandChildrenSerializer,
}
class Meta:
model = models.Parent
fields = [
'field1',
'field2',
'url',
]
class JSONAPIMeta:
included_resources = ['singleChild', 'manyGrandChildren']
...
My code does not work, because I cannot access manyGrandshildren on my response, which is something like http://host.com/api/parents/1/?include=singleChild,singleChild.manyGrandChildren also please correct me if my url ?include= statement is not correct.
How do I accomplish that?
Upvotes: 1
Views: 615
Reputation: 328
To include grandchildren in the serializer, we need to define included_serializers and included_resources on the child serializers and include grandchildren there. In that case, we can access them from parent serializer. The naughty thing is the relationship. for one-to-many relationships we need to set 'manyGrandChildren_set' as key for included_serializers and include it as 'manyGrandChildren_set' field in class Meta fields.
example
class Child(serializers.HyperlinkedModelSerializer):
included_serializers = {
'manyGrandChildren_set': manyGrandChildrenSerializer,
}
class Meta:
model = models.Child
fields = [
...
'manyGrandChildren_set'
...
]
class JSONAPIMeta:
included_resources = ['manyGrandChildren_set']
class Parent(serializers.HyperlinkedModelSerializer):
included_serializers = {
'singleChild': singleChildSerializer,
}
class Meta:
model = models.Parent
fields = [
'field1',
'field2',
'url',
]
class JSONAPIMeta:
included_resources = ['singleChild']
Upvotes: 2