Django Rest Framework Recursive Nested Parent Serialization

强颜欢笑 提交于 2019-12-23 02:34:18

问题


I have a model with a self referential field called parent. Model:

class Zone(BaseModel):
    name = models.CharField(max_length=200)
    parent = models.ForeignKey('self', models.CASCADE, blank=True, null=True, related_name='children')

    def __unicode__(self):
        return self.name

Serializer:

class ZoneSerializer(ModelSerializer):
    parent = PrimaryKeyRelatedField(many=False, queryset=Zone.objects.all())
    parent_disp = StringRelatedField(many=False, source="parent")

    class Meta:
        model = Zone
        fields = ('id', 'name', 'parent', 'parent_disp')

Now I want to serialize the parent of the zone and its parent and its parent till parent is none. I found recursive serialization methods for children but not for parent. How can I do this?


回答1:


Try use SerializerMethodField here:

def get_parent(self, obj):
    # query what your want here.

I'm not sure D-R-F has build-in methods for this, but you can use query to get what you want in this method.




回答2:


Ok, I got it working like that.

class ZoneSerializer(ModelSerializer):
    parent = SerializerMethodField()

    class Meta:
        model = Zone
        fields = ('id', 'name', 'project', 'parent',)

    def get_parent(self, obj):
        if obj.parent is not None:
            return ZoneSerializer(obj.parent).data
        else:
            return None


来源:https://stackoverflow.com/questions/39104575/django-rest-framework-recursive-nested-parent-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!