[英]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?在 Django 模型过滤中使用 group by 时,我们如何为响应中的 order by 字段设置别名/标签?
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".在上面的结果集中,我需要将“date__week_day”更改为“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:您可以直接在
values()
使用F expression
:
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:或者
ExtractWeekDay
函数,如果您只需要提取工作日:
Attendance.objects.filter(member_id=user_id, date__gte=now.date()).values(day=ExtractWeekDay('attdate')).annotate(
attendance_amount=Count('day'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.