2016-07-28 8 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ループを使用できますが、パフォーマンスは非常に悪いです。 MyModelオブジェクトをすべて選択して1つのクエリで関連するカウントを取得できる他の方法はありますか?

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

関連する問題