@@ -452,7 +452,7 @@ def get(self, request, agency_id):
452
452
453
453
qs = qs .values (* qs_values ).annotate (count = Sum ("count" )).order_by (date_precision )
454
454
if qs .count () == 0 :
455
- return Response (data = [] , status = 200 )
455
+ return Response (data = { "labels" : [], "datasets" : []} , status = 200 )
456
456
df = pd .DataFrame (qs )
457
457
unique_x_range = df [date_precision ].unique ()
458
458
pivot_df = df .pivot (index = date_precision , columns = qs_df_cols , values = "count" ).fillna (
@@ -464,6 +464,12 @@ def get(self, request, agency_id):
464
464
465
465
466
466
class AgencyStopPurposeGroupView (APIView ):
467
+ def get_values (self , df , stop_purpose , years_len ):
468
+ if stop_purpose and stop_purpose in df :
469
+ return list (df [stop_purpose ].values )
470
+ else :
471
+ return [0 ] * years_len
472
+
467
473
def get (self , request , agency_id ):
468
474
qs = StopSummary .objects .all ()
469
475
agency_id = int (agency_id )
@@ -480,30 +486,34 @@ def get(self, request, agency_id):
480
486
.annotate (count = Sum ("count" ))
481
487
.order_by ("year" )
482
488
)
489
+ if qs .count () == 0 :
490
+ return Response (data = {"labels" : [], "datasets" : []}, status = 200 )
491
+
483
492
df = pd .DataFrame (qs )
484
493
unique_years = df .year .unique ()
485
494
pivot_df = df .pivot (index = "year" , columns = "stop_purpose_group" , values = "count" ).fillna (
486
495
value = 0
487
496
)
488
497
df = pd .DataFrame (pivot_df )
498
+ years_len = len (unique_years )
489
499
data = {
490
500
"labels" : unique_years ,
491
501
"datasets" : [
492
502
{
493
503
"label" : StopPurposeGroup .SAFETY_VIOLATION ,
494
- "data" : list (df [ StopPurposeGroup .SAFETY_VIOLATION ]. values ),
504
+ "data" : self . get_values (df , StopPurposeGroup .SAFETY_VIOLATION , years_len ),
495
505
"borderColor" : "#7F428A" ,
496
506
"backgroundColor" : "#CFA9D6" ,
497
507
},
498
508
{
499
509
"label" : StopPurposeGroup .REGULATORY_EQUIPMENT ,
500
- "data" : list (df [ StopPurposeGroup .REGULATORY_EQUIPMENT ]. values ),
510
+ "data" : self . get_values (df , StopPurposeGroup .REGULATORY_EQUIPMENT , years_len ),
501
511
"borderColor" : "#b36800" ,
502
512
"backgroundColor" : "#ffa500" ,
503
513
},
504
514
{
505
515
"label" : StopPurposeGroup .OTHER ,
506
- "data" : list (df [ StopPurposeGroup .OTHER ]. values ),
516
+ "data" : self . get_values (df , StopPurposeGroup .OTHER , years_len ),
507
517
"borderColor" : "#1B4D3E" ,
508
518
"backgroundColor" : "#ACE1AF" ,
509
519
},
@@ -575,6 +585,8 @@ def get(self, request, agency_id):
575
585
.annotate (count = Sum ("count" ))
576
586
.order_by ("year" )
577
587
)
588
+ if qs .count () == 0 :
589
+ return Response (data = {"labels" : [], "datasets" : []}, status = 200 )
578
590
df = pd .DataFrame (qs )
579
591
unique_years = df .year .unique ()
580
592
pivot_table = pd .pivot_table (
0 commit comments