Django Tastypie嵌套父母/子女

时间:2013-08-25 09:43:36

标签: django tastypie

我在同一个模型中有父/子关系。 例如:

  • 家长评论
    • 儿童评论01
      • 儿童评论02

我想构建一个API,它将所有子线程都嵌入到嵌套的fasion中。 目前它只是提出了家长评论。

我目前的API.py看起来像这样:

class ThreadResource(ModelResource):
    locations = fields.ToManyField('forum.api.comments','parent', full=True)

class Meta:
    queryset = comments.objects.all()
    resource_name = 'Comments'

class comments(ModelResource):
    class Meta:
        queryset = comments.objects.all()
        resource_name = 'comms'

我在模特中这样做的方式是:

class comments(models.Model):
    title = models.CharField(max_length=255)
    parent = models.ForeignKey('self', blank=True,null=True)
    sort = models.IntegerField(default=0)
    content = models.CharField(max_length=255)

1 个答案:

答案 0 :(得分:3)

首先,您需要定义一个过滤器函数,该函数将返回父项的查询集 评论。我们称之为filter_comments_per_bundle:

def filter_comments_per_bundle(bundle);
    parent = bundle.obj
    return comments.objects.filter(parent=parent)

接下来,只需在评论模型资源中添加对self的引用:

children = fileds.ToManyField('self', filter_comments_per_bundle, full = True, null = True)

最后,抱歉,但这是一个小小的烦恼。 s /评论/评论/模型应该是单数的,首字母大写。

哦,还有一件事。不要将Models和ModelResources命名为相同。重命名评论ModelResource。

相关问题