如何在Django REST Framework中序列化与self的递归关系?

时间:2016-06-08 13:14:38

标签: python django recursion django-rest-framework serializer

考虑以下假设模型:

class Category(models.Model):
    name = models.CharField(max_length=100)
    sub_category = models.ManyToManyField(u'self', null=True, blank=True,
                                          through=u'SubCategory', symmetrical=False)

    def __unicode__(self):
        return self.name


class SubCategory(models.Model):
    from_category = models.ForeignKey(Category, related_name=u'from_category')
    to_category = models.ForeignKey(Category, related_name=u'to_category')

    def __unicode__(self):
        return self.from_category.name

我们怎么能有一个序列化器来序列化这样的递归关系:

{
    "id": 1,
    "name": "a",
    "sub_category": [
        {
            "id": 2,
            "name": "b",
            "sub_category": [
                {
                    "id": 3,
                    "name": "c",
                    "sub_category": [
                        {
                            "id": 4,
                            "name": "d",
                            "sub_category": [
                                ...
                            ],
                        },
                        ...
                    ],
                },
                ...
            ]
        },
        ...
    ]

}

1 个答案:

答案 0 :(得分:1)

我会尝试djangorestframework-recursive包,可在此处找到:https://github.com/heywbj/django-rest-framework-recursive