作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的网站页面上,我试图在 html 组件上显示每个类别中的帖子数。这是我想在下面做的一个例子。
我已经在 html 组件上添加了类别名称。类别名称旁边的值只是用作占位符的随机数。我一直在努力获得每个类别中帖子数量的值(value)。我真的不知道我想使用什么查询集。
这是我的代码。
博客.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
<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/
我是一名优秀的程序员,十分优秀!