Python 快速查询外键,django
我对以下szenario有一个性能问题: 我的模型:Python 快速查询外键,django,python,django,sqlite,Python,Django,Sqlite,我对以下szenario有一个性能问题: 我的模型: class Journey(models.Models): #... class Station(models.Model): #... class Connection(models.Model): station1 = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='station1') station2 = mode
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')
现在,我通过a*安排了一个列表,其中包含旅程(从a到b)中的相邻站点ID,我需要获得匹配的连接。我使用了这两种可能性,但两者都需要相同的时间,对于更长的旅程,时间可能超过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)
如何加快速度?您可以尝试直接编写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)
将yourapp\u connection
重放到连接表的名称
可以将两个if语句组合到一个查询:
Connection.objects.raw('SELECT * FROM yourapp_connection WHERE station1={0} AND station2={1} OR station1={1} AND station2={0}'.format(s1,s2))
这可能会使它更快