Django 2.2.4——无法让ORM模拟;分组方式;具有预期结果的SQL函数

Django 2.2.4——无法让ORM模拟;分组方式;具有预期结果的SQL函数,django,django-models,Django,Django Models,我创建了一个超级简单的示例来说明我的问题 class TestModel(MyModel): # MyModel simply adds a UUID id and created_at/updated_at... shape = models.CharField(db_index=True, max_length=100, null=False) color = models.CharField(db_index=True, max_length=100, null=

我创建了一个超级简单的示例来说明我的问题

class TestModel(MyModel):
    # MyModel simply adds a UUID id and created_at/updated_at...

    shape = models.CharField(db_index=True, max_length=100, null=False)
    color = models.CharField(db_index=True, max_length=100, null=False)

    class Meta:
        db_table = 'test_model'
我放了一些内容

select * from test_model;

                  id                  |         created_at         | updated_at |   shape   | color 
--------------------------------------+----------------------------+------------+-----------+-------
 92a04279-9dd5-40c8-a056-052456df4e56 | 2019-12-16 14:44:21.363-05 |            | Circle    | Red
 3100ed61-056a-4da1-a537-df32496c658a | 2019-12-16 14:44:21.363-05 |            | Square    | Blue
 61e2a86a-97ef-4530-a8bb-601411280ff9 | 2019-12-16 14:44:21.363-05 |            | Heart     | Blue
 3fb19a51-9e10-4214-ad63-22422e2b77f6 | 2019-12-16 14:44:21.363-05 |            | Hexagon   | Red
 945356ab-d375-4a3b-aafc-e20c5f79f6c3 | 2019-12-16 14:44:21.363-05 |            | Rectangle | Blue
 96dcfef1-7668-44da-97cc-a86e419d6936 | 2019-12-16 14:44:21.363-05 |            | Trapeze   | Red
我想要的很简单。我想知道每种不同颜色有多少种形状。所以我用SQL写

select color, count(shape) from test_model group by color;

 color | count 
-------+-------
 Red   |     3
 Blue  |     3
不管我怎么做,试图用Django/ORM/Annotate做同样的事情都是行不通的。我最后一次尝试:

colors = TestModel.objects.annotate(color_count=Count('color', distinct=True))                                                                                

 for item in colors.all(): 
    print(item.color + " " + str(item.color_count)) 
但我明白了

Blue 1
Red 1
Blue 1
Red 1
Blue 1
Red 1
我所期望的是:

Red 3
Blue 3

我在这里遗漏了什么?

您使用的是
distinct=True
,这将导致只选择一种颜色;试试这个:

TestModel.objects.values('color').annotate(count=Count('color'))

您正在使用
distinct=True
,这将导致只选择每种颜色中的一种;试试这个:

TestModel.objects.values('color').annotate(count=Count('color'))