从子视图访问祖父母数据

时间:2019-05-07 09:54:00

标签: django python-3.x django-models django-rest-framework django-views

我有Django模型,如下所示:

class Grandparent(model.Models):
    grandparent_name = models.CharField(max_length="100")
    grandparent_age  = models.IntegerField(default=10)

class Parent(model.Models):
    parent  = ForeignKey(Grandparent,default=1)
    parent_name = models.CharField(max_length="100")

class Child(model.Models):
    parent = ForeignKey(Parent,default=1)
    child_name = models.CharField(max_length="100")

我想从Child模型访问祖父母信息。我如何使用Django Rest Framework做到这一点。我想要的输出是:对于给定的孩子,也发送其父母和祖父母的信息作为响应。

1 个答案:

答案 0 :(得分:2)

Use serializer in this way...

class GrandparentSerializer(serializers.ModelSerializer):

     class Meta:
        model = Grandparent
        fields = ('__all__')


class ParentSerializer(serializers.ModelSerializer):
     parent = GrandparentSerializer()

     class Meta:
        model = Parent
        fields = ('__all__')

class ChildSerializer(serializers.ModelSerializer):
   parent = ParentSerializer()
     class Meta:
        model = Child
        fields = ('__all__')

Or provide depth =2 in child serializer to access all Foreign key details .

引荐链接:https://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization

class ChildSerializer(serializers.ModelSerializer):
     class Meta:
        model = Child
        fields = ('__all__')
        depth = 2