快速查询外键,django

时间:2017-07-18 09:21:22

标签: 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 = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='station2')

现在我通过一个*安排了一个列表,其中包含旅程中的相邻Stations_ids(从a到b),我需要获得匹配的连接。我已经使用了这两种可能性,但两者都需要相同的时间,长途旅行可能超过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)

如何让它更快?

1 个答案:

答案 0 :(得分:0)

您可以尝试直接编写sql查询而不是django工具。 试试这段代码:

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

而不是:

yourapp_connection

Connection.objects.raw('SELECT * FROM yourapp_connection WHERE station1={0} AND station2={1} OR station1={1} AND station2={0}'.format(s1,s2)) 替换为您的连接表的名称。

您可以将两个if语句组合到一个查询中:

@

这可能会让它更快。