2016-04-13 4 views
0

私は、列の値(Components)と私の行(Materials)の間に多対1の関係があるテーブルにデータを表示します。これらの列の値と列ヘッダー(ComponentTypes)の間には、さらに多対1の関係があります。スパムデータセットをDjangoのテーブルとして表示する最も効率的な方法は何ですか?

行:

materials_list = Materials.objects.all() 

列:

component_type_list = Components.objects.filter(material__in = materials_list).values("component__name") 

列タイトルの順で行の値を確立する瞬間に私は私の見解では、これに似た何かを実装しました:

for material in materials: 
    component_list = [] 
    for component_type in component_type_list: 
     try: 
      component = material.components_set.filter(component__name = component_type['component__name'])[0].weight_pct 
     except: 
      component = 0 
     component_list.append(component) 
    material.component_list_for_table = component_list 

次に、材料とcomponent_type_listをテンプレートに渡します彼は次のよう

<table> 
    <thead> 
    <tr> 
     <th>Guru ID</th> 
     <th>Material</br>Code</th> 
    {% for component_type in component_type_list %} 
     <th>{{ component_type.component__name }}</th> 
    {% endfor %} 
    </tr> 
    </thead> 
    <tbody> 
{% for material in materials %} 
    <tr> 
     <th>{{ material.GURU_ID }}</th> 
     <th>{{ material.MATERIALCODE }}</th> 
     {% for component in material.component_list_for_table %} 
     <td>{{ component|floatformat }}%</td>  
     {% endfor %} 
    </tr> 
{% endfor %} 
    </tbody> 
</table> 

だけでも、50行(潜在〜100列)で、これは非常にゆっくりと動作します。より効率的な方法がありますか?

私はコードを編集して簡略化し、完璧ではないかもしれません。

答えて

0

私の2セント:

  • あなたが持っているどのように多くのクエリと、彼らが取るどのくらいの時間をチェックするためにDjangoのデバッグツールバーを使用しています。あなたは「これは非常にゆっくりと動作します」と言いますが、データを持つことは良いことです。
  • prefetch_relatedを使用してクエリを制限しようとしましたか?
  • SQLで複雑すぎる場合は、レコードのデータを再編成するためにPythonコードを使用したいと思います。

たぶん、このような何か:

materials_list = Materials.objects.prefetch_related('components_set').prefetch_related('components_set__type').all() 

for material in material_list: 
    component_list = [] 
    # your logic here - which should run fast thanks to the prefetches. 
    material.component_list = component_list 
関連する問題