我有两个流动的模型:
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")
对于 Item X,我想获取 ItemList 中所有包含 ItemList 中的 X 的 Profile 对象的 Item 对象列表,按每个对象出现的次数排序。
到目前为止我能做的最好的是:
Item.objects.filter(user_itemlist__in = User.objects.filter(profile__ItemList = X))
这将返回我需要的所有 Item 对象的列表,并带有重复项(如果 ItemZ 出现在 ItemList 中,对于 10 个 Profile 对象,它将在查询结果中出现 10 次)。
如何按每个对象在结果中出现的次数对上述查询的结果进行排序并删除重复项?有没有“django”的方法来做到这一点?
最佳答案
profiles = Profile.objects.filter(profile__ItemList=X)
Item.objects.filter(
user_itemlist__in=profiles
).annotate(itemcount=Count('id')).order_by('-itemcount')
关于django 按出现次数排序查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2015735/