示例模型
class Category(models.Model)
name = models.CharField()
class CategoryItem(models.Model):
category = models.ForeignKey(Category)
name = models.CharField()
quantity = models.IntField()
at = models.DateTimeField()
Categories:
1, Category #1
2, Category #2
3, Category #3
Items:
ID,NAME,CATEGORY_ID,QUANTITY,AT
1,Item #1,1,100,2017.1.1
2,Item #2,1,200,2017.1.3
3,Item #3,1,300,2017.1.3
4,Item #4,2,400,2017.1.10
5,Item #5,3,500,2017.1.10
我如何按天对此进行注释并计算每个类别的“数量”
像这样
2017.1.1
- Category #1
- Quantity: 100
2017.1.3
- Category #1
- Quantity: 500
2017.1.10
- Category #2
- Quantity: 400
- Category #3
- Quantity: 500
最佳答案
如果我理解你的问题,你需要一个带有分组依据和计数(和内部联接)的 Django 查询。
尝试这样的事情:
CategoryItem.objects.filter(CategoryItem__Category__isnull=False).values('at,name').annotate(total=Count('quantity')).order_by('at')
关于python - Django 按日期分组和每个类别的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45325486/