2016-06-08 255 views
3

考慮下面的假設性模型:如何序列化與Django REST框架中的自我遞歸關係?

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": [ 
           ... 
          ], 
         }, 
         ... 
        ], 
       }, 
       ... 
      ] 
     }, 
     ... 
    ] 

} 

回答

0

我想嘗試的djangorestframework-recursive封裝,可在這裏:https://github.com/heywbj/django-rest-framework-recursive

+0

當我使用這個模塊時,我得到一個帶有異常值的RuntimeError:'__instancecheck__'超出最大遞歸深度' –

+0

正確 - 所以你可能有一個週期在一個o關係。你需要弄清楚你想如何處理這個問題。 –

+0

謝謝。你應該在DRF中嵌入這個遞歸領域 –

相關問題