How to specify which FK to use in annotation

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).


This is the SQL that gets generated, which uses the incorrect field to join on:

    `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?

I believe you’re looking for the related_name attribute on your model field.

Ah, thanks, that seems to have done it.