Django 分组 聚合

base_sql = Order.objects.filter(is_paid=True, merchant=merchant_id)

# 如果aggregate前没有values,得到的结果是一个字典

base_sql.aggregate(amount=Sum("total_amount")).get("amount")
# 如果有values, aggregate出来的是一个queryset
base_q = UserCoupon.objects.filter(
        user__merchant=merchant_id,
        created_at__date=date
    )
sq_1 = base_q.values('coupon_id').annotate(
        # 领用数量
        pickuped_count=Count('id'),
        # 使用数量
        used_count=Count('id', filter=Q(used_at__isnull=False))
    ).all()

# annotate 前必须跟values 代表以xxx分组  最后的filter代表mysql的 havving
base_sql.values("creator_id").annotate(order_count=Count('id')).filter(order_count__gte=2).count()

  

猜你喜欢

转载自www.cnblogs.com/shenwenlong/p/9389470.html