我有一个这样的PlayTrack模型,每次user
播放track
,都意味着PlayTrack
class PlayTrack(models.Model):
track = models.ForeignKey(Track, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
token = models.CharField(max_length=255, default='default_token')
那么,如何查询每个用户的播放次数?
我已经尝试过PlayTrack.objects.annotate(Count('user'), Count('track')).values('user', 'track__count')
,但它给了我类似的东西
<QuerySet [{'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, '...(remaining elements truncated)...']>
我需要的是类似的东西
{'user': 2, 'track__count': 3},{'user': 3, 'track__count': 5},{'user': 4, 'track__count': 10},
试试这个,
from django.db.models import Count
PlayTrack.objects.values('user').annotate(count=Count('id'))
这类似于SELECT user,COUNT(id) from PlayTrack GROUP BY user
SQL 查询。通过此查询,你将获得按用户分组的所有 PlayTrack 信息
-------------------------------------------------------------------------------------------------------------------------------------
我有第二个想法,track__count
正在计算track
。所以我假设你需要得到结果作为SELECT user,COUNT(track) from PlayTrack GROUP BY user
,这可能是可能的,
from django.db.models import Count
PlayTrack.objects.values('user').annotate(count=Count('track'))