在我的网站页面上,我尝试在 html 组件上显示每个类别中的帖子数量。下面是我想要执行的操作的示例。
我已经在 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/