如何返回模型以及与该模型相关的具有多对多关系的模型
我有两个型号。评论和他的“子评论”:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是不可能的。模型查询集仅由该模型类型的对象组成。不过,您可以循环返回的
Comment
并获取每个Subcomment
:It's not possible. Model querysets are only ever composed of objects of that model type. You can loop through the returned
Comment
s and get theSubcomment
s for each, though: