Djangoでviewsデータクエリをlocals()関数で最適化

2548 ワード

シーンの最適化
ビュー関数の使用(views)データをクエリーした後、コンテキストcontext、辞書、リストなどでHTMLテンプレートにデータを渡し、templateエンジンでデータを受信して解析を完了することができます.ただしcontextでデータを渡すと、異なるビュー関数で重複するクエリー文が使用される可能性がありますので、重複クエリー文をグローバル変数に設定してlocals()に合わせることができます関数を使用して、データのクエリーと転送を行います.
最適化前
def index(request):
    threatname = '      '
    url = 'www.testtip.com'
    allthreat = Threat.objects.all()
    #        
    rec = Threat.objects.filter(rec__id=1)[:3]
    #    
    threat_tags = Tag.objects.all()
    #            
    context = { 
            'threatname': threatname,
            'url': url,
            'allthreat': allthreat,
            'rec':rec,
            'threat_tags':threat_tags,
    }
    #  render        templates
    return render(request,'index.html',context)
def threatshow(request,tid):
    allthreat = Threat.objects.all()
    #        
    rec = Threat.objects.filter(rec__id=1)[:3]
    #    
    threat_tags = Tag.objects.all()
    #       
    hot_threat = Threat.objects.filter(hot__id=x)[:6]
    # sitename&url&allarticle       
    context = { 
            'allthreat': allthreat,
            'rec':rec,
            'threat_tags':threat_tags,
            'hot_threat':hot_threat,
    }
    return render(request, 'threatshow.html',context)
viewsにはindex()threatshow()の2つのビュー関数があり、この2つのビュー関数には同じデータクエリー文が3つあります.
    allthreat = Threat.objects.all()
    #        
    rec = Threat.objects.filter(rec__id=1)[:3]
    #    
    threat_tags = Tag.objects.all()

最適化後
グローバル変数の設定
    #             
def global_variable(request):
    allthreat = Threat.objects.all()
    #        
    rec = Threat.objects.filter(rec__id=1)[:3]
    #    
    threat_tags = Tag.objects.all()
    return locals()
viewsで上記のグローバル変数を定義した後、locals()関数により以下のように最適化する.
def index(request):
    threatname = '      '
    url = 'www.testtip.com'
    #  render        templates
    return render(request,'index.html',locals())
def threatshow(request,tid):
    #       
    hot_threat = Threat.objects.filter(hot__id=x)[:6]
    return render(request, 'threatshow.html',locals())
Pythonlocals()関数は、辞書タイプで現在位置のすべてのローカル変数、すなわち現在のindex()threatshow()ビュー関数で定義されたローカルデータクエリー結果を返し、グローバル変数では他の残りのデータクエリーが完了しているため、データクエリーのニーズを満たした上でビュー関数の最適化が完了します.