Order a query set in django with an annotated field and add the rest of the objects that did not match the criteria

advertisements

So this snippet practically explains what I want to do

bloc_results = bloc_results.annotate(num_mates=Count(profilebloc__profile__in=probable_mates)).order_by("-num_mates")

I know this is not possible but it was the easiest way I found to explain the situation. the variable probable_mates is a list filled with the pk's of a user table. So I have to get that number and order by it. That's no problem using filter. The thing is that using filter only retrieves the objects that match the id's on that probable_mates list, not all of them with the ones with the highest number of matches up at the top which is what I need to get. How can I do that with the Django ORM without going raw SQL? Thanks!

EDIT: I'll clarify a bit by explaining what this is doing: There are a bunch of clubs that will be added to this webapp and I need sorting by two different parameters. One is by the number of members of each club which is pretty easy. The second one if by "Club friends" so that all of the clubs are ordered by the number of common friends they have with the logged in user even if that user hasn't joined that club. Also that is not so hard. The problem is that when I get that queryset and order it it only displays the clubs that have club friends in common, not the rest. I need the ones that have club friends at the top, ordered by number of mutual club friends and the rest at the bottom, even if they don't have club friends in common.


Like akonsu said in his comment, I'm not exactly sure what you are trying to accomplish. That said, this sounds similar to this question I just answered. Adapted to your model names, does the following do what you want?

matches = bloc_results.objects.filter(profilebloc__profile__in=probable_mates)
matches = matches.annotate(Count('num_mates'))
results = matches.order_by('-num_mates')

If not, I think you need to clarify your question a bit.