From faed6e9ce207c7b397e92e518ddd29e795c97a98 Mon Sep 17 00:00:00 2001 From: Jovit-Mathew236 Date: Wed, 6 Dec 2023 22:59:50 +0530 Subject: [PATCH] [FEAT] Fix counting issue in UrlAnalyticsAPI --- api/url_shortener/url_shortener_view.py | 53 ++++++++++++++----------- 1 file changed, 29 insertions(+), 24 deletions(-) diff --git a/api/url_shortener/url_shortener_view.py b/api/url_shortener/url_shortener_view.py index b67e23dc..08bf826c 100644 --- a/api/url_shortener/url_shortener_view.py +++ b/api/url_shortener/url_shortener_view.py @@ -139,32 +139,37 @@ def get(self, request, url_id): devices = {} referrer = {} - for query in queryset: - # Counting browsers - if browsers.get(query.browser): - browsers[query.browser] += 1 - else: - browsers[query.browser] = 1 - - # Counting operating systems - if operating_systems.get(query.operating_system): - operating_systems[query.operating_system] += 1 - else: - operating_systems[query.operating_system] = 1 - - # Counting devices - if devices.get(query.device_type): - devices[query.device_type] += 1 - else: - devices[query.device_type] = 1 - - if referrer.get(query.referrer): - referrer[query.referrer] += 1 - else: - referrer[query.referrer] = 1 + if queryset.exists(): # Check if the queryset is not empty + for query in queryset: + # Counting browsers + if browsers.get(query.browser): + browsers[query.browser] += 1 + else: + browsers[query.browser] = 1 + + # Counting operating systems + if operating_systems.get(query.operating_system): + operating_systems[query.operating_system] += 1 + else: + operating_systems[query.operating_system] = 1 + + # Counting devices + if devices.get(query.device_type): + devices[query.device_type] += 1 + else: + devices[query.device_type] = 1 + + if referrer.get(query.referrer): + referrer[query.referrer] += 1 + else: + referrer[query.referrer] = 1 + + total_clicks = queryset.first().url_shortener.count + else: + total_clicks = 0 result = { - 'total_clicks': query.url_shortener.count, + 'total_clicks': total_clicks, 'browsers': browsers, 'platforms': operating_systems, 'devices': devices,