[英]Django REST JSON API: how to include nested compound documents?
Using Django REST JSON Api, ie 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). Using Django REST JSON Api, ie 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关系)。
...
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.我的代码不起作用,因为我无法在我的回复中访问 manyGrandshildren,例如http://host.com/api/parents/1/?include=singleChild,singleChild.manyGrandChildren如果我的 Z572D4E421E5E6B9BC11D815E8A02711 也请纠正我= 说法不正确。
How do I accomplish that?我该如何做到这一点?
To include grandchildren in the serializer, we need to define included_serializers and included_resources on the child serializers and include grandchildren there.要在序列化器中包含孙子,我们需要在子序列化器上定义included_serializers和included_resources并在其中包含孙子。 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.对于一对多关系,我们需要将“manyGrandChildren_set”设置为包含序列化程序的键,并将其作为“manyGrandChildren_set”字段包含在class 元字段中。
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.