Python 如何在Django中访问category_count标题的pk

Python 如何在Django中访问category_count标题的pk,python,django,Python,Django,我有一个category小部件,它使用一个view函数来计算某个类别下的帖子数量,并列出标题和数量。我把标题作为一个链接,想链接到我的分类详细信息页面,但因为它只是一个标题,而不是实际的分类对象,我似乎不知道在html的href中放什么 型号: class Category(models.Model): title = models.CharField(max_length=20) class Meta: verbose_name = "Category" verbose_na

我有一个category小部件,它使用一个view函数来计算某个类别下的帖子数量,并列出标题和数量。我把标题作为一个链接,想链接到我的分类详细信息页面,但因为它只是一个标题,而不是实际的分类对象,我似乎不知道在html的href中放什么

型号:

class Category(models.Model):
title = models.CharField(max_length=20)

class Meta:
    verbose_name = "Category"
    verbose_name_plural = "Categories"
    ordering = ['title']

def __str__(self):
    return self.title
视图:

HTML:

{%类别中的cat_count%}
{{cat.categories\uuuu title\uuuu count}}


{%endfor%}
您应该向相反方向查询:

from django.db.models import Count

def get_category_count():
    return Category.objects.annotate(post_count=Count('post'))

当然,您需要自己编写href,因为您没有提供任何想要使用的
url
/
路径。您可能最好使用“计算”href。

它起作用了!非常感谢你。我显然还在学习,我感谢你花时间来帮助我。将第二个cat.title更改为cat.post\u count,并在标题和链接旁边获得计数,url“category\u detail”pk=cat.pk请正确设置代码格式。
from django.db.models import Count

def get_category_count():
    return Category.objects.annotate(post_count=Count('post'))
{% for cat in category_count %}
    <div class="item d-flex justify-content-between">
        <a href="something with {{ cat.pk }}" class="ntd">{{ cat.title }}</a>
        <span>{{ cat.title }}</span>
    </div>
    <hr/>
{% endfor %}