2017-07-18 83 views
0

我有以下SZENARIO性能問題:使外鍵快速查詢,Django的

我的模型:

class Journey(models.Models): 
    #... 

class Station(models.Model): 
    #... 

class Connection(models.Model): 
    station1 = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='station1') 
    station2 = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='station2') 

現在我通過包含在旅途相鄰stations_ids一個*排列的列表(從a到b),我需要獲得匹配的連接。香港專業教育學院使用的那些2個possibilites,但都需要在同一時間可以是10秒以上長途旅行:

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

您可以嘗試直接編寫sql查詢,而不是django工具。 試試這個代碼:

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

取而代之的是:

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

Replase yourapp_connection你的連接表的名稱。

您可以將兩個if語句來一個查詢:

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 

同樣沒有原始的sql。

+0

謝謝你,但不幸的是它diddnt改變性能 – DarkShark