考虑简单的User
和Content
模型设置。我想分配每个用户的内容,包括0
供没有内容的用户使用
per_user | count
----------+-------
0 | 89
1 | 15
2 | 14
出于这个问题,准系统模型为:
class User(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Content(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
使用纯SQL
进行此操作的一种方法是:
SELECT
per_user,
count(per_user) count
FROM (
SELECT COUNT(c.id) per_user
FROM app_user u
LEFT JOIN app_content c ON (c.user_id = u.id)
GROUP BY u.id
) AS sub
GROUP BY
per_user
ORDER BY
per_user DESC;
我可以这样做以获得per_user
计数:
User.objects.annotate(per_user=Count("content")).values("per_user")
不幸的是,我不能在此结尾处再贴一个.annotate(c=Count("per_user"))
:
FieldError: Cannot compute Count('per_user'): 'per_user' is an aggregate