I am trying to refactor this piece of code to improve time complexity by reducing the number of loops.
items = DataActionItem.objects.filter(status='resolved', site_id=settings.SITE_ID)
resolved = []
for item in items:
init = [resolved.history_date for resolved in
item.history.filter(status='resolved',
history_date__lte=datetime.datetime.today(),
history_date__gt=datetime.datetime.today() - datetime.timedelta(
days=7)) if getattr(resolved.prev_record, 'status') != 'resolved']
resolved.append(max(init).date())
rc = Counter()
rc.update(resolved)
So far, this is what I have.
DataActionItem.history.filter(site_id =40, status='resolved',
history_date__lte=datetime.datetime.today(),
history_date__gt=datetime.datetime.today()-datetime.timedelta(days=7)).values('id',
'history_date').distinct().annotate(day=TruncDate('history_date'),
).values('day').annotate(n=Count('id')).order_by('day')
While writing this query, I got stuck at the point when I was checking the previous object. See below.
getattr(resolved.prev_record, 'status') != 'resolved'
I would like to compare each object in the query set to the last object and only return the ones that their previous history objects do not have a resolved status.
If someone can help me cut down the number of loops in the original query, that will be great.