
Django
使用Django ORM版本的SQL COUNT(DISTINCT
Pythonfrom Django.db.models import Countclass Product(models.Model): name = models.CharField(max_length=100) category = models.CharField(max_length=50)# 统计各个类别中不同产品的数量distinct_counts = Product.objects.values('category').annotate(count=Count('name')).count()print(distinct_counts)在上面的代码中,我们首先导入了Count()函数和Product模型。然后,我们使用values()方法指定我们要按照"category"字段进行分组,并使用annotate()方法结合Count()函数来计算各个类别中不同产品的数量。最后,我们调用count()方法来获取统计结果并打印输出。通过使用Django ORM版本的COUNT(DISTINCT Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号