【问题标题】:How to find object with highest number of an attribute如何找到属性数量最多的对象
【发布时间】:2023-04-04 00:47:01
【问题描述】:

例如,假设我有一个名为“ClassRoom”的模型和一个名为“Student”的模型,并且 Student 与 ClassRoom 有外键关系。

Class Student(models.Model):
    classroom = models.ForeignKey(ClassRoom, related_name='student')

如何使用基本的 Django 查询来查找哪个教室的学生最多。我为找到答案所做的工作似乎应该更容易。

max = 0    
for c in ClassRoom.objects.all():
        if c.student.count() > max:
            print 'ID: %s' % c.id
            max = c.student.count()

然后我会使用最后打印的 ID 并对教室 ID 进行 .get() 查询。反正有没有用注释或聚合来做到这一点?

【问题讨论】:

  • 你也可以发布你的模型定义吗?

标签: django django-queryset


【解决方案1】:

尝试将这样的内容添加到您的 ClassRoom 对象中:

def num_students(self):
    return Students.objects.filter(classroom=self).count()

显然将classroom 替换为您所称的任何名称。然后您应该能够使用__max 查询。

免责声明:我没有尝试过,但它在我的脑海中有效:)

【讨论】:

    猜你喜欢
    • 2021-10-05
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多