【问题标题】:Django Tastypie: including relationship with the same modelDjango Tastypie:包括与同一模型的关系
【发布时间】:2013-05-22 22:08:11
【问题描述】:

我真的被这个问题困住了。这是模型的简化版本:

# models.py
class CustomComment(models.Model):
    comment = models.CharField(max_length=500)
    parent_comment = models.ForeignKey('self', blank=True, null=True)
    active = models.BooleanField()

所以 cmets 可以有子 cmets(虽然只有两个级别)。因此,在 api 中,当我查询我想要包含孩子的评论时。我有其他模型与其他模型有关系,但我找不到如何在同一个模型中建立关系。这是我尝试过的:

# api.py
class CustomCommentResource(ModelResource):
    children = fields.ToManyField('self', 'children', related_name='parent_comment', null=True, blank=True, full=True) # returns an empty array

    class Meta:
        queryset = CustomComment.objects.filter(parent_comment=None, active=True)
        resource_name = 'comment'

当我调用 api 时使用此代码,对象确实有一个 children 属性,但它是一个空数组。

知道如何获取 cmets,每条评论包括自己的孩子吗? 谢谢

【问题讨论】:

  • 您想要分层结构中的所有 cmets(无论这些 cmets 适用于什么),还是只需要一条评论及其直系子项?
  • @Aya 对不起,我忘了准确地说,只有两个级别。只有父母和孩子 cmets,孩子不能有孩子 cmets。在回应中,我希望所有的父母都将他们所有的孩子都放在里面
  • 只是为了检查:您是否确认分配给queryset 的查询实际上返回了任何对象?我注意到您的active 字段将默认为False,但您只选择active=True 的位置。
  • @Aya 是的,该字段在创建对象时设置为 True。起初我没有想到的是,在查询中我还指定了parent_comment=None。而且孩子们不会有任何父母。但我不知道它是否与用于关系的查询相同。另外,即使我将其删除,它也不会返回任何内容

标签: python django api tastypie


【解决方案1】:

我起初没有想到的是,在查询中我 还指定parent_comment=None。孩子们不会有任何 父母。

没关系。每个家长都可以通过相关经理parent.customcomment_set 随时访问孩子。

但我不知道它是否与用于关系的查询相同。

没有。它会为每个父级执行单独的查询以获取其子级,尽管您可以使用prefetch_related() 在一个查询中执行此操作。

以下代码...

# api.py
class CustomCommentResource(ModelResource):
    children = fields.ToManyField('self', lambda bundle: bundle.obj.customcomment_set.all(), null=True, blank=True, full=True)

    class Meta:
        queryset = CustomComment.objects.filter(parent_comment=None, active=True)
        resource_name = 'comment'

...对我有用,但 ToManyField 的文档不是特别好,所以我不确定这是否是最好的方法。

【讨论】:

  • 圣烟非常感谢你,这行得通!也感谢您的解释。
猜你喜欢
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 2012-09-01
  • 2012-07-28
  • 1970-01-01
  • 1970-01-01
  • 2015-07-25
  • 1970-01-01
相关资源
最近更新 更多