Ejonas GGgg
Ejonas GGgg

Reputation: 476

Trying to get Count('foo__bar') inside annotate()

Im trying to get the following line works:

artists = models.Artists.objects.all().annotate(tot_votes=Count('votes__work')).order_by('-tot_votes')

(i.e. I want simply to annotate the count of all votes corresponding to every artist.)

But whenever the above line is executed I get the FieldError error Cannot resolve keyword 'votes' into field.

Where

class Votes(models.Model):
    work = models.OneToOneField(Works, models.DO_NOTHING, db_column='work')
    user = models.OneToOneField(AuthUser, models.DO_NOTHING, db_column='user')

and

class Works(models.Model):
    artist = models.ForeignKey(Artists, models.DO_NOTHING, db_column='artist')
    # other irrelevant fields

OR simply the relation between the tables is (Votes --> Works --> Artists)

Upvotes: 0

Views: 19

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599530

I think you've got that relationship the wrong way round, haven't you? Artist doesn't have any kind of direct relationship to Votes, it only does to Works. The annotate call should be to Count('work__votes').

(Also note that normal naming convention for Django is to use singular names: Vote, Work, Artist.)

Upvotes: 1

Related Questions