How to return model and models related to this model with many-to-many relationships

132 views Asked by At

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.

1

There are 1 answers

4
Chris Pratt On BEST ANSWER

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