尝试通过统计多个字段Django

问题描述

感谢您花时间阅读我的文章,以便让我得到重点。

我尝试按照最常用标签的顺序将最常用的标签设置为最不使用的前5个值,但我不知道如何。 这就是我尝试过的:

models.py


class Tag(models.Model):
    tag = models.CharField(max_length=250)

    def __str__(self):
        return self.tag


class BlogPost(models.Model): # blogpost_set -> queryset
    tags = models.ManyToManyField(Tag,null = True)

context_processor.py

def blog_cat_tags(request):
    # Top Tags
    most_common = BlogPost.objects.values('tags').annotate(truck_count=Count('tags')).order_by('-truck_count')
    most_common_n = Tag.objects.values('tag').annotate(truck_count=Count('tag')).order_by('-truck_count')
    common_tags = []
    for tag in most_common:
        common_tags.append(tag)
    common_tags = common_tags[:5]

这是解决方案:

enter image description here

标签按顺序排列,但我无法获得名称,如果我将 most_common 变量从更改为 most_common_n ,我会明白。

enter image description here

但这不是正确的顺序。有什么想法吗?

解决方法

您可以通过values

来获取姓名
def blog_cat_tags(request):

    most_common = BlogPost.objects.values('tags__tag').annotate(truck_count=Count(
         'tags')).order_by('-truck_count').values('tags__tag','truck_count')
    # Here you will get out put as
    # {'tags__tag':'Tag 1','truck_count':1} you can use it directly

    common_tags = []
    for tag in most_common:
        common_tags.append(tag['tags__tag'])
    common_tags = common_tags[:5]
,

很抱歉,您的回复很晚。 您可以通过以下查询来实现:

most_common = BlogPost.objects.values('tags__tag').annotate(truck_count=Count('tags')).order_by('-truck_count')[:5]

结果(most_common)为:

[
    {'tags__tag': 'tag1','truck_count': 5},{'tags__tag': 'tag2','truck_count': 4},{'tags__tag': 'tag3','truck_count': 3},{'tags__tag': 'tag4','truck_count': 2},{'tags__tag': 'tag5','truck_count': 1},]