In this question, we were given a solution to sort a query based on the intersection of two many to many fields. While it's a great answer, the restriction is that you have to filter first.
Say I have the same two models. Is there a way to annotate all results by count of intersection, so that I can display all Questions regardless of location, but still sorted by location?
class Location(models.Model):
name = models.CharField(max_length=100)
class Profile(models.Model):
locations_of_interest = models.ManyToManyField(Location)
class Question(models.Model):
locations = models.ManyToManyField(Location)
I wish I could do something like this:
from django.db.models import Count
matching_profiles = Profile.objects.all().annotate(
locnom=Count('locations_of_interest__in=question.locations.all()')
)
Any ideas? Do I just have to make two queries and merge them?