views:

49

answers:

2

Hello guys! 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 annonate Match.

This is what is working right now

User.objects.annotate(ammount=Count("match")).filter(Q(ammount__gt=0)).order_by("ammount")

And this is what I wanted to do

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

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

Thanks a lot in advance!

+1  A: 

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.

Daniel Roseman
Thanks for your reply Daniel! Ok, but isn't there anyway of selecting all users that are staff, then selecting all matches for those users and then applying some filters and aggregations?
Clash
@Clash there isn't any sensible way, but maybe you could select all Staff, get id for each user in staff and then select all Match objects that have foreign key in the list of those user ids.
rebus
+1  A: 

This wont work?

Staff.objects.annotate(ammount=Count("user__match")).filter(Q(ammount__gt=0)).order_by("ammount")
Lakshman Prasad
Genius!! Thank you very much Lakshman, this was exactly what I needed!
Clash