如何返回模型以及与该模型相关的具有多对多关系的模型

发布于 2024-11-13 09:07:49 字数 924 浏览 6 评论 0原文

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

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]
    ....

但它仅返回没有子评论的评论,并且我不知道如何使用他的“子评论”返回评论本身并按日期排序。

I have two models. Comment and his "Subcomments":

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)
    ....

I trying to make RSS subscribtion to post comments. I use following code:

class EntryCommentsFeed(Feed):

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

But It returns only Comments without subcomments, and i don't have any idea how to return comment itself with his 'subcomments' and order by date.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

疾风者 2024-11-20 09:07:49

这是不可能的。模型查询集仅由该模型类型的对象组成。不过,您可以循环返回的 Comment 并获取每个 Subcomment

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

It's not possible. Model querysets are only ever composed of objects of that model type. You can loop through the returned Comments and get the Subcomments for each, though:

for comment in Comment.not_spam.filter(post=obj).order_by('-published')[:15]:
    subcomments = comment.subcomment_set.all()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文