Clash
Clash

Reputation: 5025

Question about django model API

So, here is what I want to do. I have a model Staff, that has a foreign key to the User model. I also have a model Match that has a foreign key to the User model.

I want to select how much Matches every Staff has. I don't know how to do that, so far I only got it working for the User model. From Staff, it will not allow to annotate Match.

This is what is working right now

User.objects.annotate(amount=Count("match")).filter(Q(amount__gt=0)).order_by("amount")

And this is what I wanted to do

Staff.objects.annotate(amount=Count("match")).filter(Q(amount__gt=0)).order_by("amount")

And by the way, is there any way to filter the matches? I want to filter the matches by a certain column.

Upvotes: 0

Views: 128

Answers (2)

lprsd
lprsd

Reputation: 87077

This wont work?

Staff.objects.annotate(ammount=Count("user__match")).filter(Q(ammount__gt=0)).order_by("ammount")

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599530

If both Staff and Match have foreign keys to User, but not to each other, there is no such thing as 'how many matches each staff has'. There are several of both Staff and Match for each User, so there's simply no way of knowing which Staff for a user is related to which Match for that same user.

This isn't a limitation of Django - it's a logical limitation, imposed by the way you've structured your relationships.

Upvotes: 1

Related Questions