Django 模型 - 选择相关计数

use*_*968 5 django django-models

我有以下模型,我需要找出有多少个 OtherModel 实例指向同一个 MyModel 实例。

class MyModel(models.Model):
    int = models.SmallIntegerField()

class OtherModel(models.Model):
    other_model = models.ForeignKey(MyModel, null=True, blank=True)
    int = models.SmallIntegerField()
Run Code Online (Sandbox Code Playgroud)

我可以使用for循环,但性能很差。有没有其他方法可以选择所有 MyModel 对象,并在一个查询中获取相关计数?

for m in MyModel.objects.all(): 
       count = self.othermodel_set.count()
Run Code Online (Sandbox Code Playgroud)

Sha*_*ang 5

from django.db.models import Count

result = MyModel.objects.all().annotate(othermodel_count=Count('othermodel'))
Run Code Online (Sandbox Code Playgroud)

关于聚合功能的Django 文档。