django orm分组查询

    # 所有的分类,对应的文章数
    # pk 是这个表的主键
    # orm分组终极总结:
    # group by 谁,就以谁做基表
    # filter在前,表示where value在前,表示group by
    # filter在后,表示having,value在后,表示取字段
    from django.db.models import Count


    models.Category.objects.all().filter(blog=user.blog).values('title').\
        annotate(cateory_count=Count("pk")).\
        filter(cateory_count__gt=1).\
        values('title','cateory_count')
    ca_num=models.Category.objects.annotate(cateory_count=Count("article")).values('title','cateory_count')
    ca_num2=models.Category.objects.all().values('title').annotate(cateory_count=Count("article__title")).values('title','cateory_count')
    print(ca_num)
    print(ca_num2)

    # 当前站点下所有的分类,对应的文章数
    # ca_num=models.Category.objects.all().filter(blog=blog).annotate(cateory_count=Count("article")).values('title','cateory_count')
    ca_num = models.Category.objects.all().filter(blog=blog).annotate(cateory_count=Count("article")).values_list(
        'title', 'cateory_count', 'nid')
    print(ca_num)
    # 查询当前站点下所有的标签,对应的文章数
    tag_num = models.Tag.objects.all().filter(blog=blog).values('nid'). \
        annotate(tag_count=Count('article__title')). \
        values_list('title', 'tag_count', 'pk')
    print(tag_num)
    # 查询每个月下发表的文章数
    # 截断函数
    from django.db.models.functions import TruncMonth
    month_num = models.Article.objects.all().order_by('-create_time').filter(user=user).annotate(
        month=TruncMonth('create_time')).values('month').annotate(c=Count('month')).values_list('month', 'c')

    print(month_num)

猜你喜欢

转载自blog.csdn.net/u014248032/article/details/85722983