【问题标题】:Count error with annotate() & values() while filtering categories, repetition在过滤类别、重复时使用 annotate() 和 values() 计数错误
【发布时间】:2021-01-06 11:15:00
【问题描述】:

Django : 过滤类别时使用 annotate() 和 values() 计数错误,重复错误,因为我使用下面的计数函数过滤类别,但它分别显示会计两次。

    queryset = Blogpost \
        .objects \
        .values('categories__title') \
        .annotate(Count('categories__title'))
    return queryset 

> My function in template 

{% for cat in category_count %}
            <div class="item d-flex justify-content-between">
                <a href="#">{{ cat.categories__title }}</a><span>{{ cat.categories__title__count }}</span>
            </div>
            {% endfor %}

【问题讨论】:

  • 分享您的BlogPostCategory 模型。
  • @WillemVanOnsem class Category(models.Model): title = models.CharField(max_length=15)
  • class Blogpost(models.Model): post_id = models.AutoField(primary_key= True) title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField(upload_to='shop/images', default="") publish = models.DateTimeField(default=timezone.now) categories = models.ManyToManyField(Category) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() featured = models.BooleanField()

标签: django


【解决方案1】:

你应该按名字排序,所以:

queryset = Blogpost.objects.values('categories__title').annotate(
    Count('categories__title')
).order_by('categories__title')

但实际上不是查询Blogpost 模型是个好主意。可以从Category模型查询:

Category.objects.annotate(
    count=Count('blogpost')
)

因此,我们在这里用博文的数量注释Categorys,然后我们可以使用:

{% for cat in category_count %}
    <div class="item d-flex justify-content-between">
        <a href="#">{{ cat.title }}</a><span>{{ cat.count }}</span>
    </div>
{% endfor %}

【讨论】:

    猜你喜欢
    • 2014-07-14
    • 2021-04-10
    • 2022-06-12
    • 2018-06-13
    • 2015-10-17
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多