Repeated values in Django Query on aggregate and SUM

367 views Asked by At

I am using PyGal to render some chart on the frontend. My django-view [Function Based] somewhat looks like this :

def random_view(request):
    values_list = list()
    camera_dict = dict()
    bar_chart = pygal.Bar(spacing=60, explicit_size=True, width=2000,
                          height=800, pretty_print=True, margin=5, x_label_rotation=60, show_minor_x_labels=True)
    bar_chart.x_labels = ['8 AM', '9 AM', '10 AM', '11 AM', '12 Noon', '13 PM', '14 PM',
                          '15 PM', '16 PM', '17 PM', '18 PM', '19 PM', '20 PM', '21 PM', '22 PM', '23 PM']

    if request.method == 'GET':
        profile = Profile.objects.get(user_profile=request.user)
        store_qs = Store.objects.filter(brand_admin=profile)
        for store in store_qs:
            cam_qs = Camera.objects.filter(install_location=store)
            for cam in cam_qs:
                for x in range(10, 22):
                    value = PeopleCount.objects.filter(
                        timestamp__date='2017-09-06', timestamp__hour=x, camera=cam).aggregate(Sum('people_count_entry'))['people_count_entry__sum']  # noqa
                    values_list.append(value)
                bar_chart.add(str(cam), values_list)
        context = {'test': camera_dict, 'fun': bar_chart.render_data_uri()}

    return render(request, 'reports/report_daily.html', context)

The issue is I am getting same values for two different camera object.


Info:

For instance, if a store has two cameras let's say cam1 and cam2. I am getting same values for both the cam which should not be the case.

I don't know where I am making the mistake. Help Appreciated

Thanks in Advance :)

1

There are 1 answers

0
aumo On BEST ANSWER

The problem is that you define values_list outside the "camera" loop. What you are doing is building a list containing the values from all the cameras from all the stores. To build a list for each camera, instantiate values_list inside the "camera" loop.

#...
for cam in cam_qs:
    values_list = []
    # ...