2017-10-19 102 views
0

計算每小時事件我如何通過的路線和日期計算,每小時停止 型號:如何通過的路線和日期範圍

MyModel(models.Model): 
    route = models.Integer(... 
    on_route_time = models.TimeField(... 
    dropoff_stops = models.Integer(... 
    pickup_stops = models.Integer(... 
    date = models.DateTime(... 

我的查詢:

def stops_per_hour(date): query_set = MyModel.objects.filter(date=date).values( 'route', 'dropoff_stops','pickup_stops','on_route_time').annotate( total=(Sum('actual_stops') + Sum('pickup_stops'))).order_by('route')

這給了我:

<<QuerySet [{'route': 226, 'dropoff_stops': 84, 'pickup_stops': 0, 'on_route_time': datetime.time(5, 23), 'total': 84},{'route': 242, 'dropoff_stops': 33, 'pickup_stops': 0, 'on_route_time': datetime.time(3, 24), 'total': 33}]>> 

我忙於計算停止/小時,並將其傳遞給視圖(例如,路線226站/小時= 15.18。建議?謝謝。

回答

0

以下是我終於解決它的方法。會對改進建議感興趣。

new_set = [] 
for i in query_set: 
    time = i.get('on_route_time') 
    stops = i.get('dropoff_stops') + i.get('pickup_stops) 
    route = i.get('route') 

    try: 
     time.hour * 60 + time.minute > 0 
     sph = round(stops/(time.hour * 60 + time.minute) * 60, 1) 
     dict = {'route':route, 'sph', sph} 
     new_set.append(dict) 
    except: 
     sph = 0 
     new_set.append(dict) 
return new_set 

嘗試處理類型和除以零問題。