I figured how to fetch records for the last 30 days.
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import Record
from . import forms
from django.utils.timezone import now
from datetime import timedelta
@login_required(login_url='/users/login/')
def index(request):
last_30_days = now() - timedelta(days=30)
records = Record.objects.filter(user=request.user, creation_date__gte=last_30_days).order_by('-creation_date')
return render(request, 'core/index.html', {'records': records})
now the question how to group the results by date.
Right now it displays records. if pressure is normal - it’s green background, if high - orange, if too hight - red, if way too high - purple.
When pressure is normal I ,measure it twice - morning and evening. However when it’s too high, I measure it more often - I take a pill, I measure in a hour to check if it got normal, if not I measure in hour again etc. So the day when pressure is good has two green records. The days with high pressure have many records and they are orange and red. So when I take a look at “last 30 days records” I see a lot of bad results. I’d like “last 30 days records” shows one card for each date, colored accordingly to the highest pressure record that day.
Please help. It’s quite complicated for me as a Django noob.
P.S. Oops, it looks like I’m logged in as one user on my phone, and another on my computer. Sorry about that.
I’m also pretty new and never done this myself so I’m not sure this’ll work and might not be the full solution, but maybe something with TruncDate and annotate, like:
records = (Record.objects.filter(user=request.user, creation_date__gte=last_30_days)
.annotate(day=TruncDate('creation_date'))
.annotate(Max('pressure'))
.order_by('-day'))
where pressure is replaced with the name of the relevant field of the Record model that has the number you want the highest record of.
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import Record
from . import forms
from django.utils.timezone import now
from datetime import timedelta
from django.db.models import Max
from django.db.models.functions import TruncDate
@login_required(login_url='/users/login/')
def index(request):
last_30_days = now() - timedelta(days=30)
records = Record.objects.filter(creation_date__gte=last_30_days).annotate(day=TruncDate('creation_date')).values('day').annotate(max_sis=Max('sis'), max_dia=Max('dia')).order_by('-day')
return render(request, 'core/index.html', {'records': records})