Django equivalent of COUNT with GROUP BY

前端 未结 2 777
耶瑟儿~
耶瑟儿~ 2020-12-07 16:00

I know Django 1.1 has some new aggregation methods. However I couldn\'t figure out equivalent of the following query:

SELECT player_type, COUNT(*) FROM playe         


        
2条回答
  •  我在风中等你
    2020-12-07 16:27

    Django 1.1 does support aggregation methods like count. You can find the full documentation here.

    To answer your question, you can use something along the lines of:

    from django.db.models import Count
    q = Player.objects.annotate(Count('games'))
    print q[0]
    print q[0].games__count
    

    This will need slight tweaking depending on your actual model.

    Edit: The above snippet generates aggregations on a per-object basis. If you want aggregation on a particular field in the model, you can use the values method:

    from django.db.models import Count
    q = Player.objects.values('playertype').annotate(Count('games')).order_by()
    print q[0]
    print q[0].games__count
    

    order_by() is needed because fields that are in the default ordering are automatically selected even if they are not explicitly passed to values(). This call to order_by() clears any ordering and makes the query behave as expected.

    Also, if you want to count the field that is used for grouping (equivalent to COUNT(*)), you can use:

    from django.db.models import Count
    q = Player.objects.values('playertype').annotate(Count('playertype')).order_by()
    print q[0]
    print q[0].playertype__count
    

提交回复
热议问题