Django orm 字段别名

Django orm 数据查询结果给字段取别名

sql 写法类似:

select name as username, id as userid
from users

Django实现修改列明的方法有两种:

方法1: annotate

from django.db.models import F
 
Users.objects.filter(id=1).annotate(new_name=F('old_name'), ...).values('new_name')

方法2: extra

Users.objects.filter().extra(select={'new_name': 'old_name', 'new_f2': 'old_f2'}).values('new_name')

django 最后执行的sql:

SELECT (name) AS "username" FROM "Users" WHERE "id" = 11;
    # orm case when用法
    # whens = [When(total__gte=F('plan'), then=Value('完成'))]
    whens = [When(total__gte=500.0, then=Value('完成')), When(total__lt=300.0, then=Value('未完成'))]
    ret = models.TotalMark.objects.filter(closing_date='2022-10-01').annotate(
        level=Case(
            *whens,
            # When(total__gte=F('plan'), then=Value('完成')),
            default=Value('不知道')
        )
    )

    # print(ret.values('crew_infos_id', 'total', 'plan', 'level'))
    # 别名
    print(
        ret.extra(
            select={'班组': 'crew_infos_id', '进款': 'total', '计划': 'plan'}
        ).values(
            '班组', '进款', '计划', 'level'
        )
    )

 

posted @ 2023-01-09 17:34  笑而不语心自闲  阅读(373)  评论(0编辑  收藏  举报