[django]django models最佳实战
models
class People(models.Model):
name = models.CharField(max_length=30)
age = models.CharField(max_length=30)
def __str__(self):
return self.name
insert into app03_people (name,age) values('m1','1');
查出最小的age
使用annotate(Min('age')出错
In [1]: from django.db.models import Max,Min,Sum,Avg,Count
In [2]: from app03.models import People
In [3]: People.objects.all()
Out[3]: <QuerySet [<People: m1>, <People: m2>, <People: m3>, <People: m4>]>
In [6]: People.objects.annotate(Min('age'))
Out[6]: <QuerySet [<People: m1>, <People: m2>, <People: m3>, <People: m4>]>
In [10]: print(People.objects.annotate(Min('age')).query)
SELECT `app03_people`.`id`, `app03_people`.`name`, `app03_people`.`age`, MIN(`app03_people`.`age`) AS `age__min` FROM `app03_people` GROUP BY `app03_people`.`id` ORDER BY NULL
小结: People.objects.annotate(Min('age'))默认group by id;
使用aggregate完美解决
In [13]: print(People.objects.aggregate(Min('age'))) # 主这里无法query, 因为他返回的是字典类型.
{'age__min': '1'}
等同的sql,(聚合函数可以单独使用)
mysql> SELECT MIN(`app03_people`.`age`) AS `age__min` FROM `app03_people`;
+----------+
| age__min |
+----------+
| 1 |
+----------+
1 row in set (0.00 sec)
查询age最大最小
aggregate解决
In [15]: People.objects.aggregate(Min('age'),Max('age'))
Out[15]: {'age__min': '1', 'age__max': '4'}
等价的sql
mysql> SELECT MIN(`app03_people`.`age`) AS `age__min`,MAX(`app03_people`.`age`) AS `age__max` FROM `app03_people`;
+----------+----------+
| age__min | age__max |
+----------+----------+
| 1 | 4 |
+----------+----------+
1 row in set (0.00 sec)
annotate分组查询
In [6]: People.objects.values('part').annotate(Min('age'))
Out[6]: <QuerySet [{'part': 'UI', 'age__min': '10'}, {'part': 'python', 'age__min': '30'}, {'part': 'java', 'age__min': '40'}]>
In [7]: print(People.objects.values('part').annotate(Min('age')).query)
SELECT `app03_people`.`part`, MIN(`app03_people`.`age`) AS `age__min` FROM `app03_people` GROUP BY `app03_people`.`part` ORDER BY NULL
默认值显示两个字段(正常)
mysql> SELECT `app03_people`.`part`, MIN(`app03_people`.`age`) AS `age__min` FROM `app03_people` GROUP BY `app03_people`.`part` ORDER BY NULL
-> ;
+--------+----------+
| part | age__min |
+--------+----------+
| UI | 10 |
| python | 30 |
| java | 40 |
+--------+----------+
3 rows in set (0.00 sec)
In [17]: print(People.objects.values('part').annotate(Min('age'),Max('age')).query);
SELECT `app03_people`.`part`, MIN(`app03_people`.`age`) AS `age__min`, MAX(`app03_people`.`age`) AS `age__max` FROM `app03_people` GROUP BY `app03_people`.`part` ORDER BY NULL
mysql> SELECT `app03_people`.`part`, MIN(`app03_people`.`age`) AS `age__min`, MAX(`app03_people`.`age`) AS `age__max` FROM `app03_people` GROUP BY `app03_people`.`part` ORDER BY NULL;
+--------+----------+----------+
| part | age__min | age__max |
+--------+----------+----------+
| UI | 10 | 20 |
| python | 30 | 50 |
| java | 40 | 40 |
+--------+----------+----------+
3 rows in set (0.00 sec)
In [19]: print(People.objects.values('part').annotate(Min('age')).annotate(Max('age')).query);
SELECT `app03_people`.`part`, MIN(`app03_people`.`age`) AS `age__min`, MAX(`app03_people`.`age`) AS `age__max` FROM `app03_people` GROUP BY `app03_people`.`part` ORDER BY NULL
mysql> SELECT `app03_people`.`part`, MIN(`app03_people`.`age`) AS `age__min`, MAX(`app03_people`.`age`) AS `age__max` FROM `app03_people` GROUP BY `app03_people`.`part` ORDER BY NULL;
+--------+----------+----------+
| part | age__min | age__max |
+--------+----------+----------+
| UI | 10 | 20 |
| python | 30 | 50 |
| java | 40 | 40 |
+--------+----------+----------+
3 rows in set (0.00 sec)
以2个字段为准 分类
model
In [157]: print ChainLog.objects.values('src_svc_id', 'dst_svc_id').annotate(
...: is_success_total_count=Count('is_success')).query
SELECT `home_application_chainlog`.`src_svc_id`, `home_application_chainlog`.`dst_svc_id`, COUNT(`home_application_chainlog`.`is_success`) AS `is_success_total_count` FROM `home_application_chainlog` GROUP BY `home_application_chainlog`.`src_svc_id`, `home_application_chainlog`.`dst_svc_id` ORDER BY NULL
mysql> SELECT `home_application_chainlog`.`src_svc_id`, `home_application_chainlog`.`dst_svc_id`, COUNT(`home_application_chainlog`.`is_success`) AS `is_success_total_count` FROM `home_application_chainlog` GROUP BY `home_application_chainlog`.`src_svc_id`, `home_application_chainlog`.`dst_svc_id` ORDER BY NULL;
+------------+------------+------------------------+
| src_svc_id | dst_svc_id | is_success_total_count |
+------------+------------+------------------------+
| 1 | 1 | 2 |
| 1 | 2 | 1 |
| 2 | 3 | 1 |
| 2 | 4 | 1 |
| 3 | 5 | 1 |
+------------+------------+------------------------+
5 rows in set (0.00 sec)
如果是py字典,以2个字段为维度,不好统计
total = [
{'from':1,'to':2,'is_success':1},
{'from':1,'to':3,'is_success':0},
{'from':1,'to':4,'is_success':1}
]
faild = [
{'from':1,'to':2,'is_success':1},
{'from':1,'to':3,'is_success':0},
{'from':1,'to':4,'is_success':1}
]
[django]django models最佳实战的更多相关文章
- [django]django查询最佳实战
from django.db.models import Max, Min, Sum, Avg, Count, Q, F Django中的F和Q函数 一.F介绍 作用:操作数据表中的某列值,F()允许 ...
- Django 二——models(admin、ORM),一对一、一对多、多对多操作,all、values、value_list的对比
内容概要 1.关系对象映射ORM 2.admin的配置(选修) 3.all().values().value_list()的对比 4.数据库操作(一对一.一对多.多对多) 5.HttpResponse ...
- web框架-(七)Django补充---models进阶操作及modelform操作
通过之前的课程我们可以对于Django的models进行简单的操作,今天了解下进阶操作和modelform: 1. Models进阶操作 1.1 字段操作 AutoField(Field) - int ...
- 【Django】--Models 和ORM以及admin配置
Models 数据库的配置 1 django默认支持sqlite,mysql, oracle,postgresql数据库 <1>sqlite django默认使用sqlite的数据库 ...
- Django 之 models的 F() 和 Q() 函数
前提: app名称为core,models.py 如下: #coding: utf8 import datetime from django.db import models class Order( ...
- 【Python】django模型models的外键关联使用
Python 2.7.10,django 1.8.6 外键关联:http://www.bubuko.com/infodetail-618303.html 字段属性:http://www.cnblogs ...
- django - from django.db.models import F - class F
F() 的执行不经过 python解释器,不经过本机内存,是生成 SQL语句的执行. # Tintin filed a news story! reporter = Reporters.objects ...
- Django 1.6 最佳实践: 如何设置django项目的设置(settings.py)和部署文件(requirements.txt)
Django 1.6 最佳实践: 如何设置django项目的设置(settings.py)和部署文件(requirements.txt) 作者: Desmond Chen,发布日期: 2014-05- ...
- Django的Models(三)
ORM操作的一些进阶的方法: ################################################################## # PUBLIC METHODS T ...
随机推荐
- 【laravel5.6】The Process class relies on proc_open, which is not available on your PHP installation.
部署服务器的时候,使用composer来安装依赖.遇到了 解决办法: 在php.ini中,找到disable_functions选项,看看后面是否有proc_open函数被禁用了,如果有的话,去掉即可
- [原]openstack-kilo--issue(二十二) 虚拟机的vnc console图像调用错误
[问题点] 在打开node compute 上vm的vnc console窗口时候发现vm1-compute1调用的是vm1-controller上的vnc图像 =================== ...
- Android 更改按钮样式 Button Styles
extends:http://stackoverflow.com/questions/26346727/android-material-design-button-styles I will a ...
- python搭建简单http文件服务器
import SimpleHTTPServer import SocketServer PORT = 8000 Handler = SimpleHTTPServer.SimpleHTTPRequest ...
- Saltstack之通过grains在配置文件中赋值
案例,使用salt给客户端安装zabbix agent时需要在配置文件中自动生成主机名信息 zabbix agent安装sls zabbix-agent-install: file.managed: ...
- Eclipse中代码格式化配置
一.配置formatter 从Eclipse主菜单选择“窗口→首选项”,进入“代码格式化程序”设置页.如下图所示: 确认选择的是格式化配置是Eclipse [built-in]. 注意:编写好代码后需 ...
- Java进阶面试题大集合-offer不再是问题
Java基础 1.List 和 Set 的区别 2.HashSet 是如何保证不重复的 3.HashMap 是线程安全的吗,为什么不是线程安全的(最好画图说明多线程环境下不安全)? 4.HashMap ...
- POJ 2299 Ultra-QuickSort 离散化加树状数组求逆序对
http://poj.org/problem?id=2299 题意:求逆序对 题解:用树状数组.每读入一个数x,另a[x]=1.那么a数列的前缀和s[x]即为x前面(或者说,再x之前读入)小于x的个数 ...
- C和C指针小记(六)-基本声明、指针声明、typedef 、常量、作用域、链接属性、存储类型、static
1.变量的声明 声明变量的基本形式: 说明符号(一个或者多个) 声明表达式列表 说明符 (specifier) 包含一些关键字,用于描述被声明的标识符的基本类型,它也可用户改变标识符的缺省存储类型和作 ...
- winform 科学计数法转为小数
先强制转换为decimal. 例如: double xyTolerance = 0.000000008983001; txtXYTolerance.Text = ((decimal)xyToleran ...