django sort query result by occurrence count

django, sorting

Solution

profiles = Profile.objects.filter(profile__ItemList=X)

Item.objects.filter(
    user_itemlist__in=profiles
).annotate(itemcount=Count('id')).order_by('-itemcount')

Problem

I've got the flowing two models: ``` class Item(models.Model): Name = models.CharField(max_length = 32) class Profile(models.Model): user = models.ForeignKey(User, unique = True) ItemList = models.ManyToManyField(Item, related_name = "user_itemlist") ``` For Item X I want to get a list of Item objects present in ItemList for all Profile objects that contain X in ItemList, sorted by how many times each object appears. The best I can do so far is: ``` Item.objects.filter(user_itemlist__in = User.objects.filter(profile__ItemList = X)) ``` and this returns the list of all Item objects I need, with duplicates (if Item Z is present in ItemList for 10 Profile objects it will appear 10 times in the query result). How can I sort the result of the above query by the number of times each object appears in the result and remove duplicates? Is there any "django" way to do that?

Original source