Django的多表查詢操作實(shí)戰(zhàn)
1 > 神奇的雙下劃線查詢
1 > 查詢年齡大于20的用戶
res = modles.User.objects.filter(age__gt=20) print(res) ''' __gt 大于 __lt 小于 __gte 大于等于 __lte 小于等于 '''
2 > 查詢年齡是18、22、25的用戶
res = modles.User.objects.filter(age__in=[18, 22, 25]) print(res) ''' __in 成員運(yùn)算 '''
3 > 查詢年齡在18到26之間的用戶
res = modles.User.objects.filter(age__ranger=[18, 26]) print(res) ''' __ranger 范圍查詢 '''
4 > 查詢姓名中包含字母j的用戶
res = modles.User.objects.filter(name__contains='j') res = modles.User.objects.filter(name__icontains='j') print(res) ''' __contains 區(qū)分大小寫 __icontains 忽略區(qū)分大小寫 '''
5 > 其他方法補(bǔ)充
__startswith 以什么開頭
__endswith 以什么結(jié)尾
__regex 正則
6 > 查詢月份是5月的數(shù)據(jù)
res = models.User.objects.filter(op_time__month=5) print(res) ''' __year 按照年份篩選數(shù)據(jù) __month 按照月份篩選數(shù)據(jù) '''
2 > 外鍵字段的創(chuàng)建
MySQL復(fù)習(xí)
關(guān)系的種類
一對多關(guān)系
多對多關(guān)系
一對一關(guān)系
關(guān)系的判斷
換位思考
字段的位置
一對多關(guān)系 外鍵字段建在多的一方
多對多關(guān)系 外鍵字段建在第三張關(guān)系表中
一對一關(guān)系 外鍵字段建在任意一方都可以 但是推薦建在查詢頻率較高的表中
2.1 > 數(shù)據(jù)準(zhǔn)備
django orm創(chuàng)建表關(guān)系 圖書表 出版社表 作者表 作者詳情表 關(guān)系判斷 書與出版社 一本書不能對應(yīng)多個(gè)出版社 一個(gè)出版社可以對應(yīng)多本書 # 一對多關(guān)系 書是多 出版社是一 ForeignKey '''django orm外鍵字段針對一對多關(guān)系也是建在多的一方 ''' 書與作者 一本書可以對應(yīng)多個(gè)作者 一個(gè)作者可以對應(yīng)多本書 # 多對多關(guān)系 ManyToManyField '''django orm外鍵字段針對多對多關(guān)系 可以不用自己創(chuàng)建第三張表''' 作者與作者詳情 一個(gè)作者不能對應(yīng)多個(gè)作者詳情 一個(gè)作者詳情不能對個(gè)多個(gè)作者 # 一對一關(guān)系 OneToOneField '''django orm外鍵字段針對一對一關(guān)系 建在查詢頻率較高的表中''' 注意事項(xiàng): ''' ManyToManyField不會(huì)在表中創(chuàng)建實(shí)際的字段 而是告訴django orm自動(dòng)創(chuàng)建第三張關(guān)系表 ForeignKey、OneToOneField會(huì)在字段的后面自動(dòng)添加_id后綴 如果你在定義模型類的時(shí)候自己添加了該后綴那么遷移的時(shí)候還會(huì)再次添加_id_id 所以不要自己加_id后綴 ''' 關(guān)鍵字里面的參數(shù)說明 to: 用于指定跟哪張表有關(guān)系 自動(dòng)關(guān)聯(lián)主鍵 to_field\to_fields: 也可自己指定關(guān)聯(lián)字段
2.2 > 代碼創(chuàng)建
from django.db import models # Create your models here. class Book(models.Model): """圖書表""" title = models.CharField(max_length=32, verbose_name='書名') price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='價(jià)格') publish_time = models.DateTimeField(auto_now_add=True, verbose_name='出版日期') # 書與出版社的外鍵字段 一對多 publish = models.ForeignKey(to='Publish') # 書與作者的外鍵字段 多對多 authors = models.ManyToManyField(to='Author') def __str__(self): return '書籍對象:%s' % self.title class Publish(models.Model): """出版社""" name = models.CharField(max_length=32, verbose_name='出版社名稱') addr = models.CharField(max_length=32, verbose_name='出版社地址') def __str__(self): return '出版社對象:%s' % self.name class Author(models.Model): """作者表""" name = models.CharField(max_length=32, verbose_name='作者姓名') age = models.IntegerField(verbose_name='年齡') # 作者與作者詳情外鍵字段 一對一 author_detail = models.OneToOneField(to='AuthorDetail') def __str__(self): return '作者對象:%s' % self.name class AuthorDetail(models.Model): """作者詳情""" phone = models.BigIntegerField(verbose_name='手機(jī)號(hào)') addr = models.CharField(max_length=64, verbose_name='家庭地址') def __str__(self): return '地址詳情對象:%s' % self.addr ''' 運(yùn)行數(shù)據(jù)庫遷移命令 makemigrations migrations '''
3 > 外鍵字段操作
3.1 > 一對多、一對一外鍵字段操作
增加數(shù)據(jù) models.Book.objects.create(title='聊齋志異',price=1699.80,publish_id=1) ''' publish_id=1 author_detail_id=1 ''' publish_obj = models.Publish.objects.filter(pk=2).first() models.Book.objects.create(title='資本論',price=9566.02,publish=publish_obj) ''' publish=publish_obj author_detail=detail_obj ''' 修改數(shù)據(jù) models.Book.objects.filter(pk=11).update(publish_id=2) ''' update(publish_id=3) update(author_detail_id=3) ''' publish_obj = models.Publish.objects.filter(pk=1).first() models.Book.objects.filter(pk=11).update(publish=publish_obj) ''' update(publish=publish_obj) update(author_detail=detail_obj) '''
3.2 > 多對多字段操作
主要知識(shí)點(diǎn):
1.第三張關(guān)系表創(chuàng)建數(shù)據(jù)
book_obj = models.Book.objects.filter(pk=1).first()
book_obj.authors.add()
括號(hào)內(nèi)可以放主鍵值也可以放數(shù)據(jù)對象 并且都支持多個(gè)
2.第三張關(guān)系表修改數(shù)據(jù)
book_obj.authors.set()
括號(hào)內(nèi)必須是一個(gè)可迭代對象 元素同樣支持主鍵值或者數(shù)據(jù)對象
3.第三張關(guān)系表刪除數(shù)據(jù)
book_obj.authors.remove()
括號(hào)內(nèi)可以放主鍵值也可以放數(shù)據(jù)對象 并且都支持多個(gè)
4.第三張關(guān)系表清空指定數(shù)據(jù)
book_obj.authors.clear()
括號(hào)內(nèi)無需傳值 直接清空當(dāng)前表在第三張關(guān)系表中的綁定記錄
操做代碼如下:
book_obj = models.Book.objects.filter(pk=7).first() # 給多對多虛擬關(guān)鍵表添加關(guān)系 # book_obj.authors.add(2) authors_obj = models.Author.objects.filter(pk=2).first() authors_obj1 = models.Author.objects.filter(pk=3).first() book_obj.authors.add(authors_obj1, authors_obj) # 修改關(guān)系 book_obj = models.Book.objects.filter(pk=11).first() book_obj.authors.set([3, 6]) authors_obj1 = models.Author.objects.filter(pk=6).first() authors_obj2 = models.Author.objects.filter(pk=7).first() book_obj.authors.set([authors_obj2,authors_obj1]) # 刪除數(shù)據(jù) book_obj = models.Book.objects.filter(pk=11).first() book_obj.authors.remove(6,7) authors_obj = models.Author.objects.filter(pk=6).first() book_obj.authors.remove(authors_obj) # 清空數(shù)據(jù) book_obj.authors.clear()
4 > 多表查詢
MySQL多表查詢思路
子查詢
將SQL語句用括號(hào)括起來當(dāng)做條件使用
連表操作
inner join\left join\right join\union
django orm本質(zhì)還是使用的上述兩種方法
子查詢>>>:基于對象的跨表查詢
連表操作>>>:基于雙下劃線的跨表查詢
4.1 > 正反向的概念
核心在于當(dāng)前數(shù)據(jù)對象是否含有外鍵字段 有則是正向 沒有則是反向
正向:
eg:
由書籍查詢出版社 外鍵字段在書籍表中 那么書查出版社就是'正向'
由書籍查詢作者 外鍵字段在書籍表中 那么書查作者就是'正向'
由作者查詢作者詳情 外鍵字段在作者表中 那么也是'正向'反向
eg:
由出版社查詢書籍 外鍵字段不在出版社表 那么出版社查書就是'反向'
"""
查詢口訣
正向查詢按外鍵字段名
反向查詢按表名小寫
"""
4.2 > 基于對象的跨表查詢
操做代碼如下:
"""基于對象的跨表查詢本質(zhì)就是子查詢即分步操作即可""" # 1.查詢數(shù)據(jù)分析書籍對應(yīng)的出版社(正向 一對多) # book_obj = models.Book.objects.filter(pk=11).first() # res = book_obj.publish # print(res) # 2.查詢python全棧開發(fā)對應(yīng)的作者(正向 多對多) # book_obj = models.Book.objects.filter(pk=11).first() # res = book_obj.authors.all() # print(res) # 3.查詢作者jason的詳情信息(正向 多對多) # authors_obj = models.Author.objects.filter(name='jason').first() # res = authors_obj.author_detail # print(res) # 4.查詢東方出版社出版的書籍(反向 多對多) # publish_obj = models.Publish.objects.filter(name='東方出版社').first() # res = publish_obj.book_set.all() # print(res) # 5.查詢jason編寫的書籍(反向 多對多) # authors_obj = models.Author.objects.filter(name='jason').first() # res = authors_obj.book_set.all() # print(res) # 6.查詢電話是110的作者(反向 一對一) # authors_detail_obj = models.AuthorDetail.objects.filter(phone='110').first() # res = authors_detail_obj.author # print(res)
4.3 > 基于雙下劃線的跨表查詢
"""基于雙下劃線的跨表查詢本質(zhì)就是連表操作""" # 基于雙下劃線的跨表查詢 """ 查詢數(shù)據(jù)分析書籍對應(yīng)的價(jià)格和出版日期 models.Book.objects.filter(title='數(shù)據(jù)分析').values('price','publish_time') """ '''手上有什么條件就先拿models點(diǎn)該條件對應(yīng)的表名''' # 1.查詢數(shù)據(jù)分析書籍對應(yīng)的出版社名稱 # res = models.Book.objects.filter(title='數(shù)據(jù)分析').values('publish__name') # print(res) # 2.查詢python全棧開發(fā)對應(yīng)的作者姓名和年齡 # res = models.Book.objects.filter(title='python').values('authors__age','authors__name') # print(res) # 3.查詢作者jason的手機(jī)號(hào)和地址 # res = models.Author.objects.filter(name='jason').values('author_detail__phone','author_detail__addr') # print(res) # 4.查詢東方出版社出版的書籍名稱和價(jià)格 # res = models.Publish.objects.filter(name='東方出版社').values('book__title','book__price') # print(res) # 5.查詢jason編寫的書籍名稱和日期 # res = models.Author.objects.filter(name='jason').values('book__title','book__publish_time') # print(res) # 6.查詢電話是110的作者的姓名和年齡 # res = models.AuthorDetail.objects.filter(phone='110').values('author__name','author__age') # print(res)
4.4 > 雙下線查詢擴(kuò)展
1.查詢數(shù)據(jù)分析書籍對應(yīng)的出版社名稱 res = models.Publish.objects.filter(book__title='數(shù)據(jù)分析').values('name') print(res) # 2.查詢python全棧開發(fā)對應(yīng)的作者姓名和年齡 res = models.Author.objects.filter(book__title='python').values('name', 'age') print(res) # 3.查詢作者jason的手機(jī)號(hào)和地址 res = models.AuthorDetail.objects.filter(author__name='jason').values('phone', 'addr') print(res) # 4.查詢東方出版社出版的書籍名稱和價(jià)格 res = models.Book.objects.filter(publish__name='東方出版社').values('title', 'price') print(res) # 5.查詢jason編寫的書籍名稱和日期 res = models.Book.objects.filter(authors__name='jason').values('title', 'publish_time') print(res) # 6.查詢電話是110的作者的姓名和年齡 res = models.Author.objects.filter(author_detail__phone='110').values('name', 'age') print(res) # 連續(xù)跨表操作 # 查詢python全棧開發(fā)對應(yīng)的作者的手機(jī)號(hào) res = models.AuthorDetail.objects.filter(author__book__title='python').values('phone') print(res) res = models.Book.objects.filter(title='python').values('authors__author_detail__phone') print(res) """ 可能出現(xiàn)的不是疑問的疑問:如何獲取多張表里面的字段數(shù)據(jù) res = models.Book.objects.filter(title='python全棧開發(fā)').values('authors__author_detail__phone','authors__name','title') print(res) """
4.5 > 如何查看SQL語句
方式1:如果結(jié)果集對象是queryset 那么可以直接點(diǎn)query查看
方式2:配置文件固定配置
適用面更廣 只要執(zhí)行了orm操作 都會(huì)打印內(nèi)部SQL語句
總結(jié)
到此這篇關(guān)于Django的多表查詢操作實(shí)戰(zhàn)的文章就介紹到這了,更多相關(guān)Django多表查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python的__builtin__模塊中的一些要點(diǎn)知識(shí)
這篇文章主要介紹了Python的__builtin__模塊中的一些要點(diǎn)知識(shí),是Python學(xué)習(xí)中的基礎(chǔ),需要的朋友可以參考下2015-05-05Jupyter?notebook無法鏈接內(nèi)核、運(yùn)行代碼問題
文章主要介紹了在VSCode中使用Jupyter?Notebook遇到的問題及其解決過程,問題包括包版本沖突、文件沖突、路徑錯(cuò)誤和找不到文件,通過逐一排查和安裝相關(guān)依賴包,最終解決了這些問題,使得Jupyter?Notebook可以在VSCode中正常運(yùn)行2025-02-02python基礎(chǔ)之Numpy庫中array用法總結(jié)
NumPy(Numerical Python的縮寫)是一個(gè)開源的Python科學(xué)計(jì)算庫,使用NumPy就可以很自然地使用數(shù)組和矩陣,這篇文章主要給大家介紹了關(guān)于python基礎(chǔ)之Numpy庫中array用法的相關(guān)資料,需要的朋友可以參考下2021-08-08淺談Python2.6和Python3.0中八進(jìn)制數(shù)字表示的區(qū)別
下面小編就為大家?guī)硪黄獪\談Python2.6和Python3.0中八進(jìn)制數(shù)字表示的區(qū)別。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-04-04Python Pandas 如何shuffle(打亂)數(shù)據(jù)
這篇文章主要介紹了Python Pandas 如何shuffle(打亂)數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Python 跨文件夾導(dǎo)入自定義包的實(shí)現(xiàn)
有時(shí)我們自己編寫一些模塊時(shí),跨文件夾調(diào)用會(huì)出現(xiàn)ModuleNotFoundError: No module named 'XXX',本文就來介紹一下解決方法,感興趣的可以了解一下2023-11-11python通過自定義isnumber函數(shù)判斷字符串是否為數(shù)字的方法
這篇文章主要介紹了python通過自定義isnumber函數(shù)判斷字符串是否為數(shù)字的方法,涉及Python操作字符串判斷的相關(guān)技巧,需要的朋友可以參考下2015-04-04pandas pd.cut()與pd.qcut()的具體實(shí)現(xiàn)
本文主要介紹了pandas pd.cut()與pd.qcut()的具體實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01