I have a Django model that contains a unique record with a date . I'm currently counting records into ranges of days, e.g. X Number have already passed todays date, X will happen within the next 10 days, X will happen within the next 30 days. The code below is what I am currently using, it pulls all values back from an records.objects.all() query against the model and then loops through each object to calculate the datetime delta and increment the relevant counter.
for x in records:
if x.date is None:
missingValue += 1
else:
delta = x.date - date.today()
if delta.days < 0:
passed += 1
if delta.days < 10:
tenDays += 1
if delta.days < 30:
thirtyDays += 1
For around 50,000 records this takes about 5-6 seconds which is longer than I would like, I'm trying to reduce this as the number of records is likely to increase. The question is really around the performant calculation of datetime diffs and grouping the resultant number of days as if there is a better method through a Django Query or other method I've not been able to find I'm open to trying it.
I've explored the use of DateAdd in a raw SQL but it would appear to need me to query the database for each date range and would still lead to me needing to loop through the results.