Django:计数,分组和按顺序排列有许多场

时间:2018-08-07 16:42:03

标签: django group-by count many-to-many sql-order-by

我有两种型号:

class Actors(models.Model):
    name = models.CharField(max_length=128)
    ...


class Movies(models.Model)
    title = models.CharField(max_length=128)
    casting = models.ManyToManyField("actors.Actors", related_name="casting")
    ...

我正在通过使用演员的电影数量来订购演员。 Django会自动生成一个具有actors_id和movies_id的表,名称为movies_movies_casting:

+-----+-----------+-----------+
| id  | movies_id | actors_id |
+-----+-----------+-----------+
|   1 |         1 |         1 |
|   2 |         1 |         2 |
|   3 |         2 |         1 |
|   4 |         3 |         1 |
...

在电影#1,#2和#3中扮演的#1演员。而演员#2只在电影#1中扮演过。

这是MySQL中用于获取我想要的请求:

SELECT actors_id, COUNT(movies_id) as count FROM movies_movies_casting GROUP BY actors_id ORDER BY count;

结果是:

+-----------+-------+
| actors_id | count |
+-----------+-------+
|        15 |    29 | // actor #15 played in 29 movies
|        12 |    21 |
|        24 |    17 |
|         3 |    16 |
|        20 |    15 |
|        21 |    14 |
...

在Django中用于获得此结果的请求是什么?

1 个答案:

答案 0 :(得分:1)

尝试一下,

from django.db.models import Count

Movies.objects.values('casting'
                      ).annotate(
    count=Count('id')).order_by('-count')