Python - Django orm 字段别名

Python - Django orm 字段别名

Max.Bai

2018-11

 

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;

 

 

 

你可能感兴趣的:(Python)