我有一个名为share的表,如下所示:
+----+----------+----------+----------------+----------------------------------+
| id | users_id | files_id | shared_user_id | shared_date |
+----+----------+----------+----------------+----------------------------------+
| 2 | 1 | 2 | 2 | 2013-03-13 20:33:36.766030+00:00 |
| 4 | 1 | 4 | 2 | 2013-03-13 20:33:36.766030+00:00 |
| 5 | 1 | 5 | 2 | 2013-03-13 20:33:36.766030+00:00 |
| 6 | 1 | 6 | 2 | 2013-03-13 20:33:36.766030+00:00 |
| 8 | 1 | 2 | 2 | 2013-03-14 16:15:29.580095+00:00 |
| 10 | 1 | 4 | 2 | 2013-03-14 16:15:29.580095+00:00 |
| 11 | 1 | 5 | 2 | 2013-03-14 16:15:29.580095+00:00 |
| 12 | 1 | 6 | 2 | 2013-03-14 16:15:29.580095+00:00 |
| 13 | 1 | 7 | 2 | 2013-03-14 16:15:29.580095+00:00 |
| 14 | 1 | 8 | 2 | 2013-03-14 16:15:29.580095+00:00 |
| 15 | 1 | 9 | 2 | 2013-03-14 16:15:29.580095+00:00 |
| 16 | 1 | 12 | 2 | 2013-03-14 16:15:29.580095+00:00 |
| 18 | 1 | 2 | 2 | 2013-03-14 16:17:57.929392+00:00 |
| 20 | 1 | 4 | 2 | 2013-03-14 16:17:57.929392+00:00 |
| 21 | 1 | 5 | 2 | 2013-03-14 16:17:57.929392+00:00 |
| 22 | 1 | 6 | 2 | 2013-03-14 16:17:57.929392+00:00 |
| 23 | 1 | 7 | 2 | 2013-03-14 16:17:57.929392+00:00 |
| 24 | 1 | 8 | 2 | 2013-03-14 16:17:57.929392+00:00 |
| 25 | 1 | 9 | 2 | 2013-03-14 16:17:57.929392+00:00 |
| 26 | 1 | 12 | 2 | 2013-03-14 16:17:57.929392+00:00 |
| 27 | 1 | 12 | 2 | 2013-03-15 15:51:50.344222+00:00 |
| 28 | 1 | 9 | 3 | 2013-03-15 15:58:06.655270+00:00 |
| 29 | 1 | 2 | 2 | 2013-03-15 15:59:58.023322+00:00 |
+----+----------+----------+----------------+----------------------------------+
我想找出每个files_id
共享文件的用户总数。我怎么能这样做?
试过这个:
Share.objects.filter(users_id=request.user.id).values_list('shared_user_id', flat=True).distinct()
但这只计算shared_user_id
。
以下是我的模特:
class Share(models.Model):
users = models.ForeignKey(User)
files = models.ForeignKey(File)
shared_user_id = models.IntegerField()
shared_date = models.TextField()
class File(models.Model):
users = models.ForeignKey(User)
file_name = models.CharField(max_length=100)
type = models.CharField(max_length=10)
source = models.CharField(max_length=100)
start_date = models.TextField()
time_overview = models.CharField(max_length=55)
end_date = models.TextField()
duration = models.TextField()
size_overview = models.IntegerField()
size = models.TextField()
flag = models.TextField()
flag_r = models.TextField()
答案 0 :(得分:1)
您想使用Django的Aggregate功能。
使用您的模型,您可以:
counts = Share.objects.all().annotate(num_shares=Count("shared_user_id"))
for count in counts:
print "%s - %s shares" % (count.files, count.num_shares)
要获取特定文件的计数,假设file
是表示给定文件的对象:
count = Share.objects.filter(files=file).annotate(num_shares=Count("shared_user_id"))
print count[0].num_count
答案 1 :(得分:0)
您可以使用简单查询来计算mysql
SELECT
files_id,
count(shared_user_id) AS `Shared`
FROM mytable
GROUP BY files_id
ORDER BY files_id