2016-06-22 20 views
0

Djangoテンプレートでrelated_nameを使用して外部キーレコードを調べ、countメソッドを呼び出しました。私は非常に多くの "メイン"レコードを持っているので、テンプレート内のforループはデータベースに多すぎるクエリを作成します。データベースへのクエリの数を減らすための簡単な方法があれば?私の設定については下記をご覧ください。Django - ORMのクエリ数を減らす

# models.py 
class Main(models.Model): 
    name = models.CharField(_('Name'), max_length=255) 

class Sub1(models.Model): 
    main = models.ForeignKey(Main, on_delete=models.CASCADE) 
    name = models.CharField(_('Name'), max_length=255) 

class Sub2(models.Model): 
    main = models.ForeignKey(Main, on_delete=models.CASCADE) 
    name = models.CharField(_('Name'), max_length=255) 

class Sub3(models.Model): 
    main = models.ForeignKey(Main, on_delete=models.CASCADE) 
    name = models.CharField(_('Name'), max_length=255)  

# views.py 
def get_main(request): 
    main_list = Main.objects.all() 
    ... 

# template 
{% for main in main_list %}  
     {{main.sub1_set.count}} 
     {{main.sub2_set.count}} 
     {{main.sub3_set.count}} 
{% endfor %} 
+0

することができますフィールドにカウント値を注釈する。 https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#combining-multiple-aggregations –

答えて

2

あなたはすべて1つのクエリでこのロジックを行うためにannotationsを使用することができます:テンプレートで次に

from django.db.models import Count 

def get_main(request): 
    main_list = Main.objects.all().annotate(sub1_count=Count('sub1', distinct=True), 
              sub2_count=Count('sub2', distinct=True), 
              sub3_count=Count('sub3', distinct=True)) 

{% for main in main_list %}  
    {{ main.sub1_count }} 
    {{ main.sub2_count }} 
    {{ main.sub3_count }} 
{% endfor %} 

(編集:追加distinct

+0

の例があります。これは、すべてのフィールドで同じ結果が得られる可能性があります。それは 'Count()'呼び出しに 'distinct = True'を追加します。 –

+0

私はまだforloopの中で{{main.name}}にアクセスできますか?また、コードで "distinct = True"を使用する方法を示すことができます。ありがとう! – user1187968

関連する問題