extra
2018-01-02 本文已影响0人
lkning
a. 公司级别,查看2017每个月成单量
- 客户分配表
- 状态=成单
- 时间
```
select id,name,ctime,strftime("%Y-%m",ctime) as ftime from tb;
# select id,name,ctime,date_format(ctime,"%Y-%m") from tb;
select strftime("%Y-%m",ctime) as ftime,count('id') as ct as ftime from tb where status=2 and strftime("%Y",ctime)=2017 group by ftime
```
# 复杂SQL
- extra
models.XX.objects.extra(select={'ftime': "strftime('%%Y-%%m',ctime)"})
select
id,
name,
strftime('%Y-%m',ctime) as ftime
from
tb
models.XX.objects.extra(select={'n1': "select count(1) from tb1",'id':'id','name':'name'})
select
id,
name,
(select count(1) from tb1) as n1
from
tb
models.XX.objects.extra(select={'n1': "select count(1) from tb1 where id>%s",'id':'id','name':'name'},select_params=(11,))
select
id,
name,
(select count(1) from tb1 where id>11) as n1
from
tb
先进行字符串格式化,再执行SQL语句
```
- 原生SQL
from django.db import connection, connections
cursor = connections['default1'].cursor()
cursor = connection.cursor()
cursor.execute("""SELECT * from auth_user where id = %s""", [1])
row = cursor.fetchone()
# 实现:
from django.db.models import Count
models.CustomerDistribution.objects.filter(ctime__year=2017,status=2).extra(select={'mt':'strftime("%%Y-%%m",ctime)'}).values('mt').annotate(ct=Count('id'))
# select strftime("%Y-%m",ctime) as ftime,count('id') as ct as ftime from tb where status=2 and strftime("%Y",ctime)=2017 group by ftime
b. 公司级别,查看2017每个月成单比
v1 = models.CustomerDistribution.objects.filter(ctime__year=2017, status=2).extra(
select={'mt': 'strftime("%%Y-%%m",ctime)'}).values('mt').annotate(ct=Count('id'))
v2 = models.CustomerDistribution.objects.filter(ctime__year=2017).extra(
select={'mt': 'strftime("%%Y-%%m",ctime)'}).values('mt').annotate(ct=Count('id'))
c. 查看员工的销售记录
all_list = models.CustomerDistribution.objects.filter(ctime__gte=start_date,ctime__lte=end_date,status=2).values('user_id','ctime')
#补充
# extra
#
# extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
# Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))
# Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
# Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
# Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])