简体   繁体   中英

Django: Set an alias to the group by (annotate) field of Model.objects.filter

When group by is used on a Django Model filtering, how can we set an alias/label to the order by field in the response?

now = datetime.now()

Attendance.objects.filter(member_id=user_id, date__gte=now.date()).values('attdate__week_day').annotate(
attendance_amount=Count('attdate__week_day'))

This returns the following.

{
"attdate__week_day": 2,
"attendance_amount": 2
}

In above result set I need to change the "date__week_day" to "day". Is this possible?

Yes, use this:

Attendance.objects.filter(
    member_id=user_id, date__gte=now.date()
).annotate(
    day=F('date__week_day')
).values('day').annotate(
    attendance_amount=Count('day')
)

You can use F expression in values() directly:

Attendance.objects.filter(member_id=user_id, date__gte=now.date()).values(day=F('attdate__week_day')).annotate(
attendance_amount=Count('day'))

Or ExtractWeekDay function if you need extract only weekday:

Attendance.objects.filter(member_id=user_id, date__gte=now.date()).values(day=ExtractWeekDay('attdate')).annotate(
attendance_amount=Count('day'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM