django - 如何获取 wagtail/django 中某个类别内的项目数量?

标签 django wagtail

在我的网站页面上,我尝试在 html 组件上显示每个类别中的帖子数量。下面是我想要执行的操作的示例。

Html component displaying number of item in each category

我已经在 html 组件上添加了类别名称。类别名称旁边的值只是用作占位符的随机数。我一直在努力获取每个类别中帖子数量的值(value)。我真的不知道我应该使用什么查询集。

这是我的代码。

blog.py

class BlogPage(Page):
    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        category_slug = request.GET.get('category', None)
        blogposts = PostPage.objects.live().public().order_by('-first_published_at')
        if category_slug == None:
            context['blogposts'] = blogposts
        else:
            context['blogposts'] = blogposts.filter(categories__slug__contains=category_slug)
            context['category_slug'] = category_slug
        context['categories'] = BlogCategory.objects.all() # category object
        return context


class PostPage(Page):
    date = models.DateField(verbose_name="Post date")
    categories = ParentalManyToManyField("blog.BlogCategory", blank=True)
    body = RichTextField(blank=False)
    main_image = models.ForeignKey(
        'wagtailimages.Image', 
        null=True,
        blank=False,
        on_delete=models.SET_NULL, 
        related_name='+')

    content_panels = Page.content_panels + [
        FieldPanel('date'),
        FieldPanel('categories', widget=forms.CheckboxSelectMultiple),
        ImageChooserPanel('main_image'),
        FieldPanel('body', classname="full"),
    ]

@register_snippet
class BlogCategory(models.Model):
    name = models.CharField(max_length=120)
    slug = models.SlugField(
        verbose_name="slug",
        allow_unicode=True,
        max_length=255,
        help_text='A slug that identify post by category.'
    )

    panels = [
        FieldPanel('name'),
        FieldPanel('slug'),
    ]

    def __str__(self):
        return self.name

blog_page.html

<ul class="cat-list">
 {% for cat in categories %}
   <li>
     <a href="?category={{cat.slug}}" class="d-flex">
       <p>{{cat.name}}</p>
       <p>{{cat.count}}</p> <!-- My attempt in trying to get the number -->
     </a>
   </li>
 {% endfor %}
</ul>

最佳答案

您可以使用 Django 的 annotate 方法将计算值添加到查询集中:

https://docs.djangoproject.com/en/3.0/topics/db/aggregation/

在这种情况下,您的categories查询将变为:

from django.db.models import Count

class BlogPage(Page):
    def get_context(self, request, *args, **kwargs):
        # ...
        context['categories'] = BlogCategory.objects.annotate(num_posts=Count('postpage'))

这将允许您在模板中引用 {{cat.num_posts}}

关于django - 如何获取 wagtail/django 中某个类别内的项目数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61599829/

相关文章:

javascript - 所需属性的规范授权值

python - 使用 Heroku 部署时如何解决 "' django_content_type' does not exit” 错误?

python - Wagtail:动态图像生成和缓存

python - Django/Wagtail 一些图片上传错误500

django - 使用 Django handler404 会破坏 Wagtail 重定向

python - 如何将 Wagtail DateBlock 默认设置为当前日期

python - 在 Django 中显示数据

python - Django Order By 对反向外键值删除没有关系的项目

django - 将 HttpError 转换为 JSON

python - NoReverseMatch at/Reverse 为 'single_product',未找到任何参数。尝试了 1 个模式 : ['products/(?P<slug>)/$' ]