首页 > 其他分享 >Django orm 字段别名

Django orm 字段别名

时间:2023-01-09 17:47:10浏览次数:46  
标签:__ name 别名 Django orm Value new total id

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'
        )
    )

 

标签:__,name,别名,Django,orm,Value,new,total,id
From: https://www.cnblogs.com/vPYer/p/17037729.html

相关文章