I have an api which is supposed to get me the venue details from a set of events. There are around 10000 events and the whole process to generate the list is taking around 6.5 seconds because of which the server cpu usage shoots up to 100% and loading of the page is slow. I am using mongodb. Here is the function:
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)
If I remove the loop then the page loads in under a second. Is there any way to optimize this and bring down the loop time to minimal?
for event in events_all[:100]to only the first 100 events. You could alter the number or whether it's the events at the start or end of the list. Apart from that, you're initialising all the values as empty at the start of the loop, but they all get set after that anyway. You may as well initialise an empty dictionary to save a bit of time.eventitems havelocationas attributes, and do alllocationitems haveparentas attributes?venue_json['locat_id'] = event.location.location_idto be immediately beneath your firsttryis likely to bring the running time down somewhat.