获取主键django的问题

Issues getting primary key django

我开始学习 Django,我决定创建一个博客来检查我的技能并通过实际项目训练自己。 在我的 models.py 中有两个模型 :

class Article (models.Model):
    title = models.CharField(max_length = 100)
    author = models.CharField(max_length = 100)
    date = models.DateField(auto_now=True)
    content = models.TextField()
    is_draft = models.BooleanField(default = True)

    def __str__(self):
        return self.title

class Comment(models.Model):
    comment_author = models.CharField(max_length = 100)
    comment = models.TextField()
    article = models.ForeignKey(Article,on_delete=models.CASCADE)

    def __str__(self):
        return self.comment_author

我想显示每篇文章的所有标题和内容以及评论数,为此我使用了 ListView。 views.py :

class ArticleListView (ListView):
    context_object_name = 'articles'
    model = models.Article
    # print(models.Article.objects.get(pk=1).models.Comment_set.all())

    def get_context_data(self,**kwargs):
         context = super().get_context_data(**kwargs)
         context['title'] = models.Comment.objects.get(pk=1) # I don't know how to change this value 
         context['id'] = self.model.id 
         return context 

article_list.html :

{% for article in articles %}
    <h2>{{ article.title }}</h2>
    <p>{{ article.content }}</p>
    <h5>Id of article is {{ id }}</h5>
    <h6>{{ title }}</h6>
    {% endfor %}

我想在 Comment 上使用 count(),所以我得到 post 的评论数。为了获得文章评论列表,我认为我需要每篇文章的 pk,这样我才能找到评论的数量,但它不起作用。 你有什么办法让我解决这个问题吗?

此外,当我尝试在 get_context_data() [在 views.py] 中获取 ID 时,我得到了类似 除了数字,你知道获取实际数字的方法吗?

您可以在模板中获取所有文章及其评论的列表,而无需覆盖 get_context_data()。您可以将 related_name 传递给 ForeignKey 关系以指定它,但如果您不这样做,Django 会自动为您创建一个。为您自动创建的默认值为:comment_set。有关文档,请参阅 here

article_list.html

{% for article in articles %}
    <h2>{{ article.title }}</h2>
    <p>{{ article.content }}</p>

    <p>Total comments: {{ article.comment_set.count }}</p>
    {% for comment in article.comment_set.all %}
        <p>{{ comment.author }}</p>
        <p>{{ comment.comment }}</p>
    {% endfor %} 
{% endfor %}

不过我建议设置 related_name,然后您的模型和模板代码将是:

article = models.ForeignKey(Article,on_delete=models.CASCADE, related_name="comments")

{% for comment in article.comments %}
{% endfor %}

Here 是一个相关的 Stack Overflow post,如果您想阅读更多相关信息。