gpt4 book ai didi

django - 如何在 wagtail/django 中获取一个类别中的项目数?

转载 作者:行者123 更新时间:2023-12-04 10:05:45 24 4
gpt4 key购买 nike

在我的网站页面上,我试图在 html 组件上显示每个类别中的帖子数。这是我想在下面做的一个例子。

Html component displaying number of item in each category

我已经在 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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com