如何使用多对多关系返回与此模型相关的模型和模型

时间:2011-06-02 18:47:24

标签: django django-models django-syndication

我有两个型号。评论和他的“小组评论”:

class Comment(models.Model):

    ....
    author = models.CharField(max_length=80)
    published = models.DateTimeField(auto_now_add=True)
    email = models.EmailField(blank=True)
    url = models.URLField(blank=True)
    post = models.ForeignKey(Entry)
    subcomments = models.ManyToManyField('Subcomment', blank=True)
    ....


class Subcomment(models.Model):

    ....
    author = models.CharField(max_length=80)
    published = models.DateTimeField(auto_now_add=True)
    email = models.EmailField(blank=True)
    url = models.URLField(blank=True)
    mcomment = models.ForeignKey(Comment)
    ....

我试图让RSS订阅发表评论。我使用以下代码:

class EntryCommentsFeed(Feed):

    ....
    def items(self, obj):
        return Comment.not_spam.filter(post=obj).order_by('-published')[:15]
    ....

但它只返回没有子评论的评论,我不知道如何用他的“子评论”和按日期排序来回复评论。

1 个答案:

答案 0 :(得分:0)

这是不可能的。模型查询集只由该模型类型的对象组成。您可以遍历返回的Comment并获取每个Subcomment,但是:

for comment in Comment.not_spam.filter(post=obj).order_by('-published')[:15]:
    subcomments = comment.subcomment_set.all()