基础篇
django-orm操作
进阶操作
获取个数
#
models.Tb1.objects.filter(name='seven').count()
大于,小于
#
models.Tb1.objects.filter(id__gt=1) 获取id大于1的值
models.Tb1.objects.filter(id__gte=1) 获取id大于等于1的值
models.Tb1.objects.filter(id__lt=10) 获取id小于10的值
models.Tb1.objects.filter(id__lte=10) 获取id小于10的值
models.Tb1.objects.filter(id__lt=10, id__gt=1) 获取id大于1 且 小于10的值
in
#
models.Tb1.objects.filter(id__in=[11, 22, 33]) 获取id等于11、22、33的数据
models.Tb1.objects.exclude(id__in=[11, 22, 33]) not in
isnull
Entry.objects.filter(pub_date__isnull=True)
contains
#
models.Tb1.objects.filter(name__contains="ven")
models.Tb1.objects.filter(name__icontains="ven") icontains大小写不敏感
models.Tb1.objects.exclude(name__icontains="ven")
range
#
models.Tb1.objects.filter(id__range=[1, 2]) 范围bettwen and
其他类似
#
startswith,istartswith, endswith, iendswith,
order by
#
models.Tb1.objects.filter(name='seven').order_by('id') asc
models.Tb1.objects.filter(name='seven').order_by('-id') desc
group by
#
from django.db.models import Count, Min, Max, Sum
models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"
limit 、offset
#
models.Tb1.objects.all()[10:20]
regex正则匹配,iregex 不区分大小写
#
Entry.objects.get(title__regex=r'^(An?|The) +')
Entry.objects.get(title__iregex=r'^(an?|the) +')
date
#
Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
year
#
Entry.objects.filter(pub_date__year=2005)
Entry.objects.filter(pub_date__year__gte=2005)
month
#
Entry.objects.filter(pub_date__month=12)
Entry.objects.filter(pub_date__month__gte=6)
day
#
Entry.objects.filter(pub_date__day=3)
Entry.objects.filter(pub_date__day__gte=3)
week_day
#
Entry.objects.filter(pub_date__week_day=2)
Entry.objects.filter(pub_date__week_day__gte=2)
hour
#
Event.objects.filter(timestamp__hour=23)
Event.objects.filter(time__hour=5)
Event.objects.filter(timestamp__hour__gte=12)
minute
#
Event.objects.filter(timestamp__minute=29)
Event.objects.filter(time__minute=46)
Event.objects.filter(timestamp__minute__gte=29)
second
#
Event.objects.filter(timestamp__second=31)
Event.objects.filter(time__second=2)
Event.objects.filter(timestamp__second__gte=31)
extra
在QuerySet的基础上继续执行子语句
extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
select-select_params
例子:
tmp = models.Book.objects.all().extra(select={"n":"select count(1) from app05_book"})
for i in tmp:
print(i.title, i.n)
书一 6
书二 6
书三(第) 6
书四(第) 6
书五(第) 6
书六(第) 6
1
2
3
4
5
6
7
8
9
select占位符
tmp = models.Book.objects.all().extra(select={"n":"select count(1) from app05_book WHERE id>%s"},select_params=[3,])
for i in tmp:
print(i.title, i.n)
书一 3
书二 3
书三(第) 3
书四(第) 3
书五(第) 3
书六(第) 3
1
2
3
4
5
6
7
8
9
where-params
models.Book.objects.extra(where=["title=%s"],params=["书一"])
]>
1
2
models.Book.objects.extra(where=["title='书一' or title='书二'"])
, ]>
1
2
and关系
models.Book.objects.extra(where=["title='书一'","id=2"])
1
2
3
举个例子:
models.UserInfo.objects.extra(
select={'newid':'select count(1) from app01_usertype where id>%s'},
select_params=[1,],
where = ['age>%s'],
params=[18,],
order_by=['-age'],
tables=['app01_usertype']
)
"""
select
app01_userinfo.id,
(select count(1) from app01_usertype where id>1) as newid
from app01_userinfo,app01_usertype
where
app01_userinfo.age > 18
order by
app01_userinfo.age desc
"""
# 执行原生SQL
# 更高灵活度的方式执行原生SQL语句
# from django.db import connection, connections
# cursor = connection.cursor() # cursor = connections['default'].cursor()
# cursor.execute("""SELECT * from auth_user where id = %s""", [1])
# row = cursor.fetchone()
QuerySet高级操作
去重
def distinct(self, *field_names)
models.Book.objects.values("title").distinct()
select_related实现表之间进行一对一和多对一优化
def select_related(self, *fields)
性能相关:表之间进行join连表操作,一次性获取关联的数据。
总结:
1. select_related主要针一对一和多对一关系进行优化。
2. select_related使用SQL的JOIN语句进行优化,通过减少SQL查询的次数来进行优化、提高性能。
实例代码如下:
tmp = models.Book.objects.all()
for i in tmp:
print(i.publisher.name)
沙河出版社
沙河出版社
三里屯
五道口
国贸
五道口
a2 = models.Book.objects.all().select_related("publisher")
for i in a2:
print(i.publisher.name)
沙河出版社
沙河出版社
五道口
五道口
三里屯
国贸
以上代码中第一种查询方式会查询数据库六次,第二种方式会查询数据库次数为1次
prefetch_related实现表之间进行一对多和多对多优化
只能正向查询~且不能跨表
def prefetch_related(self, *lookups)
性能相关:多表连表操作时速度会慢,使用其执行多次SQL查询在Python代码中实现连表操作。
总结:
1. 对于多对多字段(ManyToManyField)和一对多字段,可以使用prefetch_related()来进行优化。
2. prefetch_related()的优化方式是分别查询每个表,然后用Python处理他们之间的关系。
实例代码如下:
tmp = models.Author.objects.all().prefetch_related("books")
for i in tmp:
print(i.books.all())
, ]>
, ]>
]>
defer
def defer(self, *fields):
models.UserInfo.objects.defer('username','id')
或
models.UserInfo.objects.filter(...).defer('username','id')
#映射中排除某列数据
实例代码如下:
a = models.Author.objects.all().defer("name")
for i in a:
print(i)
小一
小二
小三
小四
a = models.Author.objects.all().defer("name").values()
for i in a:
print(i)
{'id': 1, 'name': '小一', 'author_detail_id': 1}
{'id': 2, 'name': '小二', 'author_detail_id': 2}
{'id': 3, 'name': '小三', 'author_detail_id': 3}
{'id': 4, 'name': '小四', 'author_detail_id': 4}
a = models.Author.objects.all().defer(“name”).values()
虽然在查询中排除name字段,但是在循环中如果要输出关于name的信息,那么依然会继续查询输出name
only
def only(self, *fields):
#仅取某个表中的数据
models.UserInfo.objects.only('username','id')
或
models.UserInfo.objects.filter(...).only('username','id')
示例代码如下:
a = models.Author.objects.only("name")
for i in a:
print(i)
小一
小二
小三
小四
raw执行原生SQL
执行原生SQL
tmp = models.Author.objects.raw("select * from app05_author")
for i in tmp:
print(i.name)
小一
小二
小三
小四
为原生SQL设置参数
a = models.Book.objects.raw("select id from app05_book WHERE id>%s",params=[3,])
for i in a:
print(i)
书四(第)
书五(第)
书六(第)
dates
def dates(self, field_name, kind, order='ASC'):
# 根据时间进行某一部分进行去重查找并截取指定内容
# kind只能是:"year"(年), "month"(年-月), "day"(年-月-日)
# order只能是:"ASC" "DESC"
# 并获取转换后的时间
- year : 年-01-01
- month: 年-月-01
- day : 年-月-日
models.DatePlus.objects.dates('ctime','day','DESC')
示例代码如下:
models.Book.objects.all().dates("publish_day","year","DESC")
models.Book.objects.all().dates("publish_day","month","DESC")
models.Book.objects.all().dates("publish_day","day","DESC")
datetimes
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
# 根据时间进行某一部分进行去重查找并截取指定内容,将时间转换为指定时区时间
# kind只能是 "year", "month", "day", "hour", "minute", "second"
# order只能是:"ASC" "DESC"
# tzinfo时区对象
models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.UTC)
models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.timezone('Asia/Shanghai'))
"""
pip3 install pytz
import pytz
pytz.all_timezones
pytz.timezone(‘Asia/Shanghai’)
"""
bulk_create
参数为一次性插入的个数
objs = [models.Publisher(name="aaa",addr="aaa"),models.Publisher(name="bbb",addr="bbb")]
models.Publisher.objects.bulk_create(objs,2)
[, ]
get_or_create
# 如果存在,则获取,否则,创建
# defaults 指定创建时,其他字段的值
models.Publisher.objects.get_or_create(name="沙河出版社")
(, False)
models.Publisher.objects.get_or_create(name="沙河出版社1")
(, True)
models.Publisher.objects.get_or_create(name="沙河出版1",addr="sss")
(, True)
models.Publisher.objects.get_or_create(name="沙河版1",defaults={"addr":"sdfsdsf"})
(, True)
update_or_create
如果存在,则更新,否则,创建
defaults 指定创建时或更新时的其他字段
obj, created = models.UserInfo.objects.update_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 1})
in_bulk
# 根据主键ID进行查找
id_list = [11,21,31]
models.DDD.objects.in_bulk(id_list)
from app05 import models
models.Book.objects.in_bulk([1,2,3])
(0.000) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.001) SELECT VERSION(); args=None
(0.002) SELECT `app05_book`.`id`, `app05_book`.`title`, `app05_book`.`price`, `app05_book`.`publish_day`, `app05_book`.`publisher_id` FROM `app05_book` WHERE `app05_book`.`id` IN (1, 2, 3); args=(1, 2, 3)
{1: , 2: , 3: }
创建普通用户:
D:\shen\python\PythonWebDev\DRF\management 的目录
2019/10/21 14:17
(drf-venv-3.7) D:\shen\python\PythonWebDev\DRF\management>python manage.py shell
>>> from django.contrib.auth.models import User
>>>
>>> User.objects.create_user(username='test', password='test123')
>>> from django.contrib.auth import authenticate
章节1Vue基础
课时1【Vue基础】VSCode介绍13:10
课时2【Vue基础】Vue体验14:46
课时3【Vue基础】v-bind属性绑定12:09
课时4【Vue基础】VSCode添加自定义代码片段11:54
课时5【Vue基础】Class和Style属性绑定15:30
课时6【Vue基础】执行JavaScipt表达式10:03
课时7【Vue基础】v-if条件判断15:36
课时8【Vue基础】v-show和v-if11:00
课时9【Vue基础】v-for循环数组和对象12:25
课时10【Vue基础】v-for状态保持14:54
课时11【Vue基础】触发视图更新17:32
课时12【Vue基础】触发视图更新补充06:12
课时13【Vue基础】事件绑定24:35
课时14【Vue基础】计算属性20:01
课时15【Vue基础】监听属性05:45
课时16【Vue基础】表单输入绑定15:50
课时17【Vue基础】自定义组件基本使用08:46
课时18【Vue基础】组件中添加属性13:52
课时19【Vue基础】组件中自定义事件18:20
课时20【Vue基础】组件中自定义v-model行为14:40
课时21【Vue基础】自定义组件-插槽10:40
课时22【Vue基础】自定义组件-命名插槽07:05
课时23【Vue基础】自定义组件-插槽作用域14:53
课时24【Vue基础】Vue生命周期函数-创建阶段14:29
课时25【Vue基础】Vue生命周期函数-运行阶段04:08
课时26【Vue基础】Vue生命周期函数-销毁阶段08:52
课时27【Vue基础】Vue过滤器10:39
课时28【Vue基础】图书管理系统(1)21:27
课时29【Vue基础】图书管理系统(2)08:30
章节2Vue-Router
课时30【VueRouter】基本使用21:18
课时31【VueRouter】动态路由14:22
课时32【VueRouter】组件复用14:00
课时33【VueRouter】404错误配置13:30
课时34【VueRouter】路由嵌套(子路由)19:12
课时35【VueRouter】编程式导航20:28
课时36【VueRouter】命名视图15:31
课时37【VueRouter】重定向和别名05:58
课时38【VueRouter】全局导航守卫19:32
课时39【VueRouter】路由导航守卫03:44
课时40【VueRouter】组件导航守卫15:25
章节3Vue-Cli
课时41【VueCli】环境搭建-node的安装11:00
课时42【VueCli】环境搭建-npm的使用15:13
课时43【VueCli】vuecli项目讲解20:01
课时44【VueCli】组件定义和本地样式21:40
课时45【VueCli】sass语法配置04:55
课时46【VueCli】sass语法讲解16:19
课时47【VueCli】rem布局原理和配置15:34
课时48【VueCli】vant组件库的安装和使用08:47
章节4移动端美团外卖项目实战
课时49【美团项目】项目初始化12:49
课时50【美团项目】项目初始化总结06:05
课时51【美团项目】iconfont的使用07:46
课时52【美团项目】首页-header布局和样式实现09:00
课时53【美团项目】首页-商家排序操作栏完成16:44
课时54【美团项目】首页-商家列表完成12:48
课时55【美团项目】tabbar搭建17:49
课时56【美团项目】商家详情-导航栏和header布局22:41
课时57【美团项目】商家详情-tab标签页完成03:19
课时58【美团项目】商家详情-商品分类滚动完成28:28
课时59【美团项目】商家详情-商品滚动完成15:43
课时60【美团项目】商家详情-分类和商品左右联动(1)21:42
课时61【美团项目】商家详情-分类和商品左右联动(2)12:57
课时62【美团项目】商家详情-tabbar状态切换和导航返回06:01
课时63【美团项目】商家详情-查看商品详情(1)18:01
课时64【美团项目】商家详情-查看商品详情(2)22:34
课时65【美团项目】商家详情-查看商品详情(3)05:07
课时66【美团项目】商家详情-商品个数计步器实现15:00
课时67【美团项目】商家详情-购物车实现(1)11:10
课时68【美团项目】商家详情-购物车实现(2)16:58
课时69【美团项目】商家详情-购物车实现(3)09:28
课时70【美团项目】Vuex讲解20:37
课时71【美团项目】Vuex管理购物车数据08:07
课时72【美团项目】导航栏组件的封装21:28
课时73【美团项目】地址管理-地址展示08:08
课时74【美团项目】地址管理-地址列表10:45
课时75【美团项目】地址管理-添加地址09:58
课时76【美团项目】地址管理-编辑地址12:13
课时77【美团项目】提交订单完成07:24
课时78【美团项目】登陆页面完成18:32
章节5Django Rest Framework
课时79【DRF】DRF介绍和安装08:04
在windows上安装mysqlclient方法如下:
1. 浏览器访问这个链接:https://www.lfd.uci.edu/~gohlke/pythonlibs/
mysqlclient-1.4.4-cp37-cp37m-win32.whl
2. 搜索mysqlclient。
3. 根据自己Python的版本下载不同的mysqlclient版本。(查看Python版本的方法为:在cmd终端输入python,可以看到,并且要注意到底是32位还是64位的)。
4. 下载后,然后在cmd中,进入到这个文件所在的路径,输入pip install mysqlclient.whl即可安装。
5. pip3 install -r requirements.txt -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
在centos7上安装mysqlclient方法如下:
yum install mysql-devel
pip install mysqlclient
macos安装:
brew info openssl
If you need to have [email protected] first in your PATH run:
echo 'export PATH="/Users/shen/work/tools/brew-master/opt/[email protected]/bin:$PATH"' >> ~/.zshrc
For compilers to find [email protected] you may need to set:
export LDFLAGS="-L/Users/shen/work/tools/brew-master/opt/[email protected]/lib"
export CPPFLAGS="-I/Users/shen/work/tools/brew-master/opt/[email protected]/include"
shen@shendeMacBook-Pro common_channels % cat ~/.bash_profile
export LDFLAGS="-L/Users/shen/work/tools/brew-master/opt/[email protected]/lib"
export CPPFLAGS="-I/Users/shen/work/tools/brew-master/opt/[email protected]/include"
(channels) shen@shendeMacBook-Pro common_channels % source ~/.bash_profile
在此安装mysqlclient
(channels) shen@shendeMacBook-Pro common_channels % pip install mysqlclient
Looking in indexes: http://pypi.douban.com/simple/
Collecting mysqlclient
Downloading http://pypi.doubanio.com/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz (85kB)
|████████████████████████████████| 92kB 1.3MB/s
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient ... done
Successfully installed mysqlclient-1.4.6
WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
课时80【DRF】项目准备工作06:49
课时81【DRF】DRF快速入门16:35
课时82【DRF】序列化-序列化的定义17:42
课时83【DRF】序列化-序列化的使用16:34
课时84【DRF】序列化-模型序列化04:59
课时85【DRF】序列化-序列化的嵌套16:36
models.py
class NetElementManager(models.Model):
"""网元管理"""
name = models.CharField(verbose_name="设备名称", max_length=100, unique=True)
ip = models.CharField(verbose_name="设备IP", max_length=50, unique=True)
user = models.ForeignKey(NetElementUserManager,
on_delete=models.SET_NULL, null=True)
device_type = models.ForeignKey(
NetElementCustom, on_delete=models.SET_NULL, null=True)
location_info = models.CharField(
verbose_name="位置信息", max_length=50, unique=True)
net_element = models.ForeignKey(
NetElement, on_delete=models.SET_NULL, null=True)
data_center = models.ForeignKey(
DataCenter, on_delete=models.SET_NULL, null=True)
def __str__(self):
return "< {} {} {} >".format(self.name, self.ip, self.user)
class Meta():
db_table = "tbl_net_element_manager"
verbose_name = "网元管理"
# unique_together = [['name', 'ip', 'version']]
serializer.py
class NetElementManagerSerializer(serializers.ModelSerializer):
name = serializers.CharField(required=True, max_length=50, error_messages={
"blank": "请输入name", "required": "name为必填字段", "max_length": "50", "min_length": ""})
ip = serializers.CharField(required=True, max_length=50, error_messages={
"blank": "请输入ip", "required": "ip为必填字段", "max_length": "50", "min_length": ""})
user = NetElementUserManagerSerializer(read_only=True)
user_id = serializers.IntegerField(required=True, write_only=True)
device_type = NetElementCustomSerializer(read_only=True)
device_type_id = serializers.IntegerField(required=True, write_only=True)
location_info = serializers.CharField(required=True, max_length=50, error_messages={
"blank": "请输入location_info", "required": "location_info为必填字段", "max_length": "50", "min_length": ""})
net_element = NetElementSerializer(read_only=True)
net_element_id = serializers.IntegerField(required=True, write_only=True)
data_center = DataCenterSerializer(read_only=True)
data_center_id = serializers.IntegerField(required=True, write_only=True)
class Meta:
model = NetElementManager
fields = "__all__"
# exclude = ['url']
def validate(self, attrs):
print(attrs)
res = self._validate_user_id(attrs.get("user_id"))
res = self._validate_device_type_id(attrs.get("device_type_id"))
res = self._validate_net_element_id(attrs.get("net_element_id"))
res = self._validate_data_center_id(attrs.get("data_center_id"))
return attrs
def _validate_user_id(self, value):
print("value")
if not NetElementUserManager.objects.filter(pk=value).exists():
raise serializers.ValidationError("user_id不存在")
return value
def _validate_device_type_id(self, value):
print("value")
if not NetElementCustom.objects.filter(pk=value).exists():
raise serializers.ValidationError("device_type_id不存在")
return value
def _validate_net_element_id(self, value):
print("value")
if not NetElement.objects.filter(pk=value).exists():
raise serializers.ValidationError("net_element_id不存在")
return value
def _validate_data_center_id(self, value):
print("value")
if not DataCenter.objects.filter(pk=value).exists():
raise serializers.ValidationError("data_center_id不存在")
return value
def create(self, validated_data):
user = NetElementUserManager.objects.get(
pk=validated_data.get("user_id"))
device_type = NetElementCustom.objects.get(
pk=validated_data.get("device_type_id"))
net_element = NetElement.objects.get(
pk=validated_data.get("net_element_id"))
data_center = DataCenter.objects.get(
pk=validated_data.get("data_center_id"))
net_element_m = NetElementManager.objects.create(
**validated_data, user=user, device_type=device_type, net_element=net_element, data_center=data_center)
return net_element_m
课时86【DRF】请求和响应09:46
课时87【DRF】类视图-APIView使用详解11:02
课时88【DRF】类视图-Mixin使用详解16:00
课时89【DRF】类视图-GenericAPIView使用详解13:38
课时90【DRF】类视图-ViewSet视图集14:48
课时91【DRF】权限认证-认证流程分析20:56
课时92【DRF】权限认证-手动实现JWT认证(1)11:52
课时93【DRF】权限认证-手动实现JWT认证(2)10:45
课时94【DRF】权限认证-权限管理17:12
课时95【DRF】限速节流(1)13:36
课时96【DRF】限速节流(2)08:29
章节6前后端结合项目实战
课时97【美团后台】element-ui安装和配置06:30
课时98【美团后台】登录页面实现18:17
课时99【美团后台】后台首页布局实现15:31
课时100【美团后台】用户模型定义11:46
课时101【美团后台】服务端登录逻辑实现