在python中缓慢循环

时间:2015-11-30 12:22:11

标签: python mongodb python-2.7

我有一个api应该从一系列活动中获取场地细节。大约有10000个事件,生成列表的整个过程大约需要6.5秒,因为服务器CPU使用率高达100%,页面加载速度很慢。我正在使用mongodb。这是功能:

def get_venue():
events_all = Event.objects.all()
locality = ""
venue = []
data = ({'success':False, 'venue': venue})
for event in events_all:
    venue_json = {'venue_name':"", 'local':"", 'locat_id':""}
    try:
        try:
            venue_json['venue_name'] = event.location.location_name
        except Exception as e:
            venue_json['venue_name'] = ""
        try:
            venue_json['local'] = event.location.parent.location_name
        except Exception as e:
            venue_json['local'] = ""
        venue_json['locat_id'] = event.location.location_id
        venue.append(venue_json)
    except Exception as e:
        continue
if len(venue) > 0:
    data['success'] = True
return json.dumps(data)

如果我删除循环,那么页面会在一秒钟内加载。有没有办法优化这个并将循环时间缩短到最小?

1 个答案:

答案 0 :(得分:1)

使用select_related,您可以避免在for循环中进行额外的数据库查找(请参阅文档:https://docs.djangoproject.com/en/1.8/ref/models/querysets/#select-related):

events_all = Event.objects.all().select_related('location__parent')