2016-07-28 98 views
1

我有以下模型,我需要找出有多少个OtherModel实例指向同一个MyModel实例。Django模型 - 选择相关计数

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

class OtherModel(models.Model): 
    other_model = models.ForeignKey(MyModel, null=True, blank=True) 
    int = models.SmallIntegerField() 

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

for m in MyModel.objects.all(): 
     count = self.othermodel_set.count() 

回答

3
from django.db.models import Count 

result = MyModel.objects.all().annotate(othermodel_count=Count('othermodel')) 

Django的文档约aggregation features