4

consider the below assumptive models:

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

How could We have a serializer to serialize a recursion relationship like this:

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

}
iraj jelodari
  • 3,118
  • 3
  • 35
  • 45

1 Answers1

0

I'd try the djangorestframework-recursive package, available here: https://github.com/heywbj/django-rest-framework-recursive

Tom Christie
  • 33,394
  • 7
  • 101
  • 86
  • 1
    When I used this module, I got a RuntimeError with Exception Value: `maximum recursion depth exceeded in __instancecheck__` – iraj jelodari Jun 08 '16 at 15:39
  • Right - so you probably have a cycle in one of the relationships. You need to figure out how you want the representation to deal with that. – Tom Christie Jun 09 '16 at 10:27
  • thank you. you should embed this recursive field in DRF – iraj jelodari Jun 09 '16 at 11:27
  • 2
    It's better left as a third party package - helps us to spread the maintainance & documentation tasks across a wider range of people, rather than having to provide for a huge number of possible use-cases directly in the core package. – Tom Christie Jun 09 '16 at 14:36