Sql 获取相关对象数最多的对象

Sql 获取相关对象数最多的对象,sql,django,postgresql,django-models,django-orm,Sql,Django,Postgresql,Django Models,Django Orm,是否可以获取相关对象数量最多的对象 我想选择最常用的计划,这是一个拥有最多UserPlan对象的计划 我可以得到数字,但不能得到实例 number_of_users = Plan.objects.aggregate(max_users=Max('userplan'))['max_users'] 代码: class UserPlan(Model): plan = ForeignKey('Plan'..) class Plan(Model): ... @staticmeth

是否可以获取相关对象数量最多的对象

我想选择最常用的计划,这是一个拥有最多
UserPlan
对象的计划

我可以得到数字,但不能得到实例

number_of_users = Plan.objects.aggregate(max_users=Max('userplan'))['max_users']
代码:

class UserPlan(Model):
   plan = ForeignKey('Plan'..)

class Plan(Model):
   ...

    @staticmethod
    def favorite(self):
        number_of_users = Plan.objects.aggregate(max_users=Max('userplan'))['max_users']
        # ?

我可以用loop找到它,但速度可能很慢。

因为信息已经存储在一个列中,我们就对它进行排序怎么样

obj_most_popular=Plan.objects.order_by('userplan').first()

您可以在以下文档中了解更多信息: