fix: Fix mood count calculation and query formatting

Improves calculation of average mood by counting valid mood
entries (moodcount) separately, ensuring division occurs only
on valid mood data. Additionally, refines queryset management
for better readability and consistency, ensuring accurate date
range filters.

This change enhances data accuracy and code maintainability.
This commit is contained in:
Kumi 2024-11-28 16:59:31 +01:00
parent 95b4a15f15
commit 68acfc8875
Signed by: kumi
GPG key ID: ECBCC9082395383F

View file

@ -45,20 +45,18 @@ class StatusListView(LoginRequiredMixin, ListView):
return context return context
def get_queryset(self): def get_queryset(self):
status_list = Status.objects.filter(user=self.request.user).order_by("timestamp") status_list = Status.objects.filter(user=self.request.user).order_by(
"timestamp"
)
if "from" in self.request.GET: if "from" in self.request.GET:
from_timestamp = datetime.strptime(self.request.GET["from"], "%Y-%m-%d") from_timestamp = datetime.strptime(self.request.GET["from"], "%Y-%m-%d")
status_list = status_list.filter( status_list = status_list.filter(timestamp__gte=from_timestamp)
timestamp__gte=from_timestamp
)
if "to" in self.request.GET: if "to" in self.request.GET:
to_timestamp = datetime.strptime(self.request.GET["to"], "%Y-%m-%d") to_timestamp = datetime.strptime(self.request.GET["to"], "%Y-%m-%d")
to_timestamp = to_timestamp.replace(hour=23, minute=59, second=59) to_timestamp = to_timestamp.replace(hour=23, minute=59, second=59)
status_list = status_list.filter( status_list = status_list.filter(timestamp__lte=self.request.GET["to"])
timestamp__lte=self.request.GET["to"]
)
return status_list return status_list
@ -586,12 +584,13 @@ class MoodCountHeatmapJSONView(LoginRequiredMixin, View):
for entry in data: for entry in data:
date = entry.timestamp.strftime("%Y-%m-%d") date = entry.timestamp.strftime("%Y-%m-%d")
if "date" not in output: if date not in output:
output[date] = {"count": 0, "total": 0} output[date] = {"count": 0, "total": 0, "moodcount": 0}
if entry.mood: if entry.mood:
output[date]["total"] += entry.mood.value output[date]["total"] += entry.mood.value
output[date]["moodcount"] += 1
output[date]["count"] += 1 output[date]["count"] += 1
output = [ output = [
@ -599,7 +598,9 @@ class MoodCountHeatmapJSONView(LoginRequiredMixin, View):
"date": key, "date": key,
"count": value["count"], "count": value["count"],
"average": ( "average": (
(value["total"] / value["count"]) if value["count"] > 0 else 0 (value["total"] / value["moodcount"])
if value["moodcount"] > 0
else 0
), ),
} }
for key, value in output.items() for key, value in output.items()