简体   繁体   English

Django:为Model.objects.filter的(注释)字段设置一个别名

[英]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.

相关问题 是否有等效于Django Model.objects.filter()的CherryPy? - Is there a CherryPy equivalent to Django Model.objects.filter()? Django从模型中过滤:Model.objects.filter(Q()) - Django filtering from models: Model.objects.filter(Q()) 在Django Model.objects.filter()中使用动态变量 - Using dynamic variable in Django Model.objects.filter() Django:Model.objects.filter() 返回一个空的查询集 - Django: Model.objects.filter() returns an empty Queryset Django:model.objects.create()更改先前的model.objects.filter()的结果集 - Django: model.objects.create() changes the previous model.objects.filter()'s resultset django | model.objects.filter(user = request.user) 不返回任何数据 - django | model.objects.filter(user = request.user) not returning any data 从另一个进程保存对象时,在Model.objects.filter()之后需要Django transaction.commit() - Django transaction.commit() needed after Model.objects.filter() when object was saved from another process django Model.objects.filter(feildname = 'some_column') 与 Model.objects.all().filter(feildname = 'some_column') - django Model.objects.filter(feildname = 'some_column') vs Model.objects.all().filter(feildname = 'some_column') which one performs better 使用django 1.8持续时间字段注释一组django对象 - Using django 1.8 duration field to annotate a set of django objects Django - 如何在注释中使用过滤器对相关的 Model 字段求和? - Django - How to SUM the related Model field with Filter in Annotate?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM