Django通过子模型计数(一对多关系)对父模型进行排序

标签 django django-models django-queryset

假设我们有Django模型ParentChildChild属于一个Parent,一个Parent可以有多个子代。

class Parent(models.Model):
   pass

class Child(models.Model):
  parent = models.ForeignKey(Parent)

我想按 child 数量获得所有 parent 的集合。

最佳答案

child_setrelated_name模型中parent字段的默认Child。如果您指定了其他代码,则必须相应地更改代码。

from django.db.models import Count

ordered_parents = Parent.objects.annotate(num_children=Count('child_set')).order_by('-num_childen')

希望能帮助到你。

关于Django通过子模型计数(一对多关系)对父模型进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18374758/

相关文章:

django - 使用 Django 的鼠标悬停工具提示

python - django 托管错误,关于alwaysdata.com

django m2m_changed 信号通过模型自定义

python - 为什么 error_messages 在元类中不起作用?

python - 从 Django 查询集中获取 Django 值,其中列名是一个变量

sql - Django 。数据库查询: distinct for one field

django - 在 Django 中检索 OneToOne 相关的 QuerySet

jquery - 如何延迟重定向到页面,直到数据加载到 django 或 jquery 中?

python - django annotate - 条件计数

python - Django rest framework api - 图片 url 未正确返回