V
V
Vitaly2016-07-06 22:26:56
Django
Vitaly, 2016-07-06 22:26:56

How to display all "attached" comments in an article?

Greetings. Need help displaying all the comments on a page that are linked to a particular article.

Article Model:

class Article(models.Model):

    title = models.CharField(max_length=255, verbose_name=u'Заголовок')
    text = models.TextField(verbose_name=u'Текст')
    author = models.ForeignKey(settings.AUTH_USER_MODEL)
    rating = models.IntegerField(default=0, verbose_name=u'Рейтинг')
    pub_date = models.DateField(auto_now_add=True)

Comment model:
class Comment(models.Model):

    text = models.TextField(verbose_name='Текст')
    pub_date = models.DateField(auto_now_add=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL)
    article = models.ForeignKey(to=Article, on_delete=models.CASCADE)

Article detail view function:
def detail_art_view(request, a_id=1):

    article = Article.objects.get(id=a_id)
    comments = Comment.objects.all()
    context = {'Article': article, 'com_list': comments}
    return render(request, 'detail.html', context)

The problem is that I get all questions from all articles on all pages with articles (I don’t know how to filter). Google and the documentation did not help. I'm just learning and asking for help.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sim3x, 2016-07-06
@MrCute

comments = Comment.objects.filter(article=a_id)

R
Roman Kitaev, 2016-07-06
@deliro

some_article.comment_set.all()
The name of the manager for feedback can be overridden by related_name:
And then:
some_article.comments.all()

R
Rostislav Grigoriev, 2016-07-06
@crazyzubr

comments = Comment.objects.filter(article=article)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question