2017-07-18 5 views
0

を作ります(aからbへ)と一致する接続を取得する必要があります。アイブ氏は、これらの2 possibilitesを使用しますが、両方の長い旅のために10秒以上にすることができ、同時に必要があります。私は、次のszenario上のパフォーマンスの問題を持っている外部キーの高速クエリ、ジャンゴ

for i in range(0, len(journey)-1): 
    try: 
     connection = Connection.objects.get(station1_id=journey[i], station2_id=journey[i+1]) 
    except Connection.DoesNotExist: 
     try: 
      connection = Connection.objects.get(station1_id=journey[i+1], station2_id=journey[i]) 
     except Connection.DoesNotExist: 
       pass 
    journey.connections.add(connection) 

for i in range(0, len(journey)-1): 
    s1 = Station.objects.get(id = journey[i]) 
    s2 = Station.objects.get(id= journey[i+1]) 
    if (Connection.objects.filter(station1=s1, station2=s2).exists()): 
     connection = Connection.objects.get(station1=s1, station2=s2) 
    elif (Connection.objects.filter(station1=s2, station2=s1).exists()): 
     connection = Connection.objects.get(station1=s2, station2=s1) 
    journey.connections.add(connection) 

がどのように私はそれを速くすることができますか?

答えて

0

djangoツールの代わりにSQLクエリを直接書くことができます。あなたの接続テーブルの名前に

Connection.objects.get(station1=s1, station2=s2) 

Replase yourapp_connection:この代わりの

Connection.objects.raw('SELECT * FROM yourapp_connection WHERE station1={0} AND station2={1}'.format(s1,s2)) 

: このコードを試してみてください。

あなたは1つのクエリーにif文2を組み合わせることができます:

Connection.objects.raw('SELECT * FROM yourapp_connection WHERE station1={0} AND station2={1} OR station1={1} AND station2={0}'.format(s1,s2)) 

これは、それが速くなるかもしれないです。

0
from django.db.models import Q 

cross_journey = zip(journey[:-1], journey[1:]) 
for s1, s2 in cross_journey: 
    # Where like (station1=s1 AND station2=s2) OR (station1=s2 AND station2=s1) 
    qf = Q(station1_id=s1, station2_id=s2) | Q(station1_id=s2, station2_id=s1) 
    try: 
     connection = Connection.objects.get(qf) 
     journey.connections.add(connection) 
    except Connection.DoesNotExist: 
     pass 

raw SQLを使用しない場合と同じです。

+0

ありがとうございますが、残念ながらそれはパフォーマンスを変更しませんでした – DarkShark

関連する問題