I am trying to query some data across several models, to get a count of how many times a file has been shared. Let’s say the Share model has two fields that are both foreign keys to the User model:
class Share(models.Model):
file = models.ForeignKey(File...)
from_user = models.ForeignKey(User...)
to_user = models.ForeignKey(User...)
I want a list of Users, annotated with the Count of how many times they have shared a file. I am interested in the user who shared the file (from_user), not the user the file was shared with (to_user).
User.objects.annotate(share_count=Count('share'))
This is the SQL that gets generated, which uses the incorrect field to join on:
FROM
`user`
LEFT OUTER JOIN
`share` ON (`user`.`id` = `share`.`to_user_id`)
GROUP BY `user`.`id`
I can’t seem to understand why Django chooses ‘to_user_id’ over ‘from_user_id’, nor did I find any way in the documentation to specify which field to join on, if there are multiple fields that could be used.
Is there something I’m missing?