[Answer]-Count number of shared users to the given file in django?

0👍

You can use a simple query to count in mysql

SELECT
    files_id,
    count(shared_user_id) AS `Shared`
FROM mytable
GROUP BY files_id
ORDER BY files_id

1👍

You want to use Django’s Aggregate functionality.

Using your models, you could do:

counts = Share.objects.all().annotate(num_shares=Count("shared_user_id"))
for count in counts:
    print "%s - %s shares" % (count.files, count.num_shares)

To get the counts for a specific file, assuming file is an object representing a given file:

count = Share.objects.filter(files=file).annotate(num_shares=Count("shared_user_id"))
print count[0].num_count

Leave a comment