【问题标题】:django ORM return top 10 match in manytomany relationshipdjango ORM 返回多对多关系中的前 10 名匹配
【发布时间】:2018-07-14 03:53:02
【问题描述】:

我的 models.py 在UserTag 之间存在多对多关系

class Tag(models.Model):
    name = models.CharField(unique=True, max_length=32)

class User(AbstractBaseUser, PermissionsMixin):
    tags = models.ManyToManyField(Tag, blank=True)    

如何获得按使用标签的用户数量排序的前 10 个标签?类似的东西

Tag.objects.order_by('user_set__count')[10]

这个命令不起作用,django 抱怨说

django.core.exceptions.FieldError:无法将关键字“myuser_set”解析为字段。选项有:id、myuser、name

这令人费解,因为t1.user_set.count()t1Tag 实例的情况下起作用。

另外,有没有更好的方法来获得前 10 名而无需对所有数据进行排序?

【问题讨论】:

    标签: django manytomanyfield sql-limit


    【解决方案1】:

    以下查询返回按用户数排序的标签列表:

    tags = Tag.objects.all().annotate(num_user = Count('user')).order_by('-num_user')
    

    如果您想要前 10 个,请使用以下查询:

    tags = Tag.objects.all().annotate(num_user = Count('user')).order_by('-num_user')[:10]
    

    【讨论】:

      猜你喜欢
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      • 2014-12-14
      • 2017-07-18
      • 2011-06-27
      • 2018-11-09
      相关资源
      最近更新 更多