'Django how to get the value of other fields in annotate Max?
I want to get the value of other fields('status') in annotate Max or Min,how can I do it?
DB
| user | time | status |
|---|---|---|
| name_a | 2022-01-03 11:23:40.000000 | 3 |
| name_a | 2022-01-03 17:56:41.000000 | 4 |
| name_a | 2022-01-03 22:24:28.000000 | 1 |
| name_a | 2022-01-04 08:24:28.000000 | 4 |
| name_a | 2022-01-04 17:34:19.000000 | 4 |
| name_b | 2022-01-03 08:29:18.000000 | 1 |
| name_b | 2022-01-03 17:34:39.000000 | 4 |
# data_1 = Attendance.objects.filter(user__in=user_list)
data_2 = data_1.values('user', 'time__date').annotate(count=Count('time__date')).annotate(s_time=Min("time")).annotate(e_time=Max("time"))
#print
{'user': 'name_a', 'time__date': datetime.date(2022, 1, 3), 'count': 3, 's_time': datetime.datetime(2022, 1, 3, 11, 23, 40), 'e_time': datetime.datetime(2022, 1, 3, 22, 24, 28)}
i want to get:
{'user': 'name_a', 'time__date': datetime.date(2022, 1, 3), 'count': 3, 's_time': datetime.datetime(2022, 1, 3, 11, 23, 40), 'e_time': datetime.datetime(2022, 1, 3, 22, 24, 28), 's_status': '3', 'e_status': '1' }
I tried adding filter but I didn't succeed
data_2 = data_1.values('user', 'time__date').annotate(count=Count('time__date')).annotate(s_time=Min("time"), e_time=Max("time")).annotate(s_status=F("status"),filter=Q(time=Min("time"))).annotate(e_status=F("status"),filter=Q(time=Max("time")))
Solution 1:[1]
You can use Attendance.objects.order_by('time').first().status - get status of min date. And use Attendance.objects.order_by('time').last().status - get status of max date.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Airat Ahunov |
