django-orm框架
一.orm基本配置
1.創(chuàng)建django項目
- 命令行:cmd先去到django創(chuàng)建目錄,然后輸入
django-admin startproject django項目名稱 - pycharm就直接創(chuàng)建新project選擇django
2.settings.py文件配置
1.需要在install_app中配置需要連接的app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app_mysql.apps.AppMysqlConfig', #這個是我們pycharm創(chuàng)建時候自動幫我們注冊的就是app配置
'app_mysql', #如果有新的或者命令行創(chuàng)建的app我們只要這這里面把app名稱寫上去即可
]
推薦Python大牛在線分享技術(shù) 扣qun:855408893
領(lǐng)域:web開發(fā),爬蟲,數(shù)據(jù)分析,數(shù)據(jù)挖掘,人工智能
零基礎(chǔ)到項目實戰(zhàn),7天學(xué)習上手做項目
2. 需要在database中進行配置連接mysql的用戶名和密碼以及數(shù)據(jù)庫
DATABASES = {
'default':{
'ENGINE':'django.db.backends.sqlite3', #sqlite3數(shù)據(jù)庫是個小型的數(shù)據(jù)庫
'NAME':os.path.join(BASE_DIR,'sqlite3') #NAME填寫路徑即可
}
# 'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME':'庫名',
# 'USER':'mysql賬號名稱',
# 'PASSWORD':'mysql密碼',
# 'HOST':'127.0.0.1',
# }
}
3.init的配置
import pymysql
pymysql.install_as_MySQLdb()
4.modelse文件配置
配置表單信息
from django.db import models
# Create your models here.
class sb(models.Model):
### 主鍵自增id不用寫, 默認會加上
name = models.CharField(max_length=30,null=True)
class big_sb(models.Model):
name = models.CharField(max_length=30, null=True)
bigsb = models.ForeignKey('sb',id)
class sb2(models.Model):
name = models.CharField(max_length=30,null=True)
5.生成表單語句
在命令行進行操作
- python manage.py makemigrations
- python manmge.py migrate
二.orm框架的表單的增刪改查
必須先在邏輯業(yè)務(wù)層中載入
from 表單所在的app名稱 import models
其中表名均為再modelse中配置的表的名稱
1.增
-
單條數(shù)據(jù):
- 方法一 : models.表名.objects.create(字段1=值1,字段2=值2........)
- 方法二:dict = {'字段1':值,'字段2':值.........};models.表名.objects.create(**dict)
-
多條數(shù)據(jù):
info = [ models.UserInfo(name='root1', age=34, ut_id=1), models.UserInfo(name='root2', age=35, ut_id=2), models.UserInfo(name='root3', age=36, ut_id=1), models.UserInfo(name='root4', age=37, ut_id=3), models.UserInfo(name='root5', age=32, ut_id=1), ] models.UserInfo.objects.bulk_create(info)
2.刪
models.表名.objects.filter(滿足的條件).delete()
3.改
models.表名.objects.filter(滿足的條件).update(name='lll', age=23)
4.查
models.UserType.objects.all().values()
表A的ud關(guān)聯(lián)表b
有子健關(guān)系的查詢正向查詢通過A表中的ud查到表b的id
方法一:models.A.objects.all().values('ud__id')
-
方法二
res = models.A.objects.all() for a in res: print(a.ud.id)
有子健關(guān)系的查詢返向查詢通過b表中的查到a表ID
方法一:models.B.objects.all().values('A__id')
-
方法二:
res = models.B.objects.all() for b in res: print(b.a_set.id) #### 表名小寫_set
三.orm進階查詢
1.字段名過濾
filter滿足條件的
exclude不滿足條件
用法:
#id等于3的
models.表名.objects.filter(id=3).values()
#id不等于3的
models.表名.objects.exclude(id=3).values()
關(guān)于filter與exclude里面填寫的參數(shù)
等于:字段名=值
大于:字段名__gt=值
大于等于:字段名__gte=值
小于:字段名__lt=值
小于等于:字段名__lte=值
2.成員in not in
res = models.表名.objects.filter(字段名__in=[2,4,5]) # where id in (2,4,5)
res = models.表名.objects.exclude(字段名__in=[1,2]) # where id not in (1,2)
3.區(qū)間between...and
# where id between 4 and 8 [4,8]
res = models.表名.objects.filter(字段名__range=[4,8])
4.模糊查詢like
# where name like 'a%'
res = models.表名.objects.filter(字段名__startswith="a")
res = models.表名.objects.filter(字段名__istartswith="a") #忽略大小寫
# where name like '%a'
res = models.表名.objects.filter(字段名__endswith="a")
res = models.表名.objects.filter(字段名__iendswith="a") #忽略大小寫
# where name like '%a%'
res = models.表名.objects.filter(字段名__contains="a")
res = models.表名.objects.filter(字段名__icontains="a") #忽略大小寫
只要是i開頭的基本上都是忽略大小寫
5.數(shù)據(jù)條數(shù)count
# select count(*) from userinfo where id>3;
# select count(id) from userinfo where id>3;
#用sql語句查詢數(shù)據(jù)條數(shù)盡量不要查count(*)查主鍵會快很多
res = models.UserInfo.objects.filter(id__gt=3).count()
6.排序order by
#升序
res = models.表名.objects.order_by('字段名稱')
#降序
res = models.表名.objects.order_by('-字段名稱')
#多個條件進行排序
res = models.表名.objects.order_by('字段1','字段2') #當字段1相同是會更具字段2進行排序
7.分組group by已經(jīng)having
# select id, sum(age) as s, username from userinfo group by username
from django.db.models import Count, Min, Max, Sum
res = models.UserInfo.objects.values("name").annotate(s=Sum('age'))
# select id, sum(age) as s, username from userinfo group by username having s > 50;
res = models.UserInfo.objects.values("name").annotate(s=Sum('age')).filter(s__gt=50)
8.分頁limit
# limit 1, 3 分頁
res = models.UserInfo.objects.all()[1:4]
#因為獲取對象是列表所有切片即可
9.last/first
第一條:res = models.表名.objects.first()
最后一條:res = models.表名.objects.last()
10.only|defer
只查某個字段:only('字段名稱')
除某個字段以外的所有字段:defer('字段名')
注意:主鍵id不管怎么樣都會查
12.and|or
只有and
#id等于3and名字等于a
models.表名.objects.filter(id=3,and name='a').values()
只有or
# Q
from django.db.models import Q
res = models.UserInfo.objects.filter(Q(id__gt=3) | Q(name='zekai')) #or用|鏈接
有and和or
# Q
from django.db.models import Q
res = models.UserInfo.objects.filter( Q(Q(id__gt=3) | Q(name='zekai')) & Q(age=23) ) and用&鏈接
13.F
from django.db.models import F
models.UserInfo.objects.update(name=F('name')+1) #字段名稱都加1
14.原生sql 類似pymysql
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()
print(row)
15.去重distinct
models.UserInfo.objects.values("name", 'age').distinct() #前面values有多少個就對多少個值進行去除
四.補充一個小點
print(res.query) 查看上述代碼生成的sql語句