Django按日期和按类别计数

时间:2017-07-26 11:21:14

标签: python mysql django

示例模型

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

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你想要一个带分组依据和计数(和内连接)的Django查询。

尝试这样的事情:

CategoryItem.objects.filter(CategoryItem__Category__isnull=False).values('at,name').annotate(total=Count('quantity')).order_by('at')