我有以下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)
我怎樣才能使它更快嗎?
謝謝你,但不幸的是它diddnt改變性能 – DarkShark