python - Django 按日期分组和每个类别的计数

标签 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

最佳答案

如果我理解你的问题,你需要一个带有分组依据和计数(和内部联接)的 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/

相关文章:

python - 将图片与 QGraphicsItem 关联

python - 无法使用 pyplot、pandas : _tkinter. TclError 绘制图形:无显示名称且无 $DISPLAY 环境变量

python - 使用 Django 内置表单上传图像

django - verbose_name_plural 命名约定

python - 使用 Google App Engine 和 Jinja2 的 TemplateNotFound : index. html

python - Selenium 打印 A4 格式的 PDF

python - 如何在Kivy中开始/使用Matplotlib

php - Mysql `select` 查询中的运算符问题

Mysql表超过2000列

python - Django 数组字段。如何通过 django admin 保存嵌套的时间数组?