Django的多表查詢操作實戰(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 成員運算 '''
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)多個出版社 一個出版社可以對應(yīng)多本書 # 一對多關(guān)系 書是多 出版社是一 ForeignKey '''django orm外鍵字段針對一對多關(guān)系也是建在多的一方 ''' 書與作者 一本書可以對應(yīng)多個作者 一個作者可以對應(yīng)多本書 # 多對多關(guān)系 ManyToManyField '''django orm外鍵字段針對多對多關(guān)系 可以不用自己創(chuàng)建第三張表''' 作者與作者詳情 一個作者不能對應(yīng)多個作者詳情 一個作者詳情不能對個多個作者 # 一對一關(guān)系 OneToOneField '''django orm外鍵字段針對一對一關(guān)系 建在查詢頻率較高的表中''' 注意事項: ''' ManyToManyField不會在表中創(chuàng)建實際的字段 而是告訴django orm自動創(chuàng)建第三張關(guān)系表 ForeignKey、OneToOneField會在字段的后面自動添加_id后綴 如果你在定義模型類的時候自己添加了該后綴那么遷移的時候還會再次添加_id_id 所以不要自己加_id后綴 ''' 關(guān)鍵字里面的參數(shù)說明 to: 用于指定跟哪張表有關(guān)系 自動關(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='價格')
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ī)號')
addr = models.CharField(max_length=64, verbose_name='家庭地址')
def __str__(self):
return '地址詳情對象:%s' % self.addr
'''
運行數(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 > 多對多字段操作
主要知識點:
1.第三張關(guān)系表創(chuàng)建數(shù)據(jù)
book_obj = models.Book.objects.filter(pk=1).first()
book_obj.authors.add()
括號內(nèi)可以放主鍵值也可以放數(shù)據(jù)對象 并且都支持多個
2.第三張關(guān)系表修改數(shù)據(jù)
book_obj.authors.set()
括號內(nèi)必須是一個可迭代對象 元素同樣支持主鍵值或者數(shù)據(jù)對象
3.第三張關(guān)系表刪除數(shù)據(jù)
book_obj.authors.remove()
括號內(nèi)可以放主鍵值也可以放數(shù)據(jù)對象 并且都支持多個
4.第三張關(guān)系表清空指定數(shù)據(jù)
book_obj.authors.clear()
括號內(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語句用括號括起來當(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)的價格和出版日期
models.Book.objects.filter(title='數(shù)據(jù)分析').values('price','publish_time')
"""
'''手上有什么條件就先拿models點該條件對應(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ī)號和地址
# res = models.Author.objects.filter(name='jason').values('author_detail__phone','author_detail__addr')
# print(res)
# 4.查詢東方出版社出版的書籍名稱和價格
# 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ī)號和地址
res = models.AuthorDetail.objects.filter(author__name='jason').values('phone', 'addr')
print(res)
# 4.查詢東方出版社出版的書籍名稱和價格
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ī)號
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 那么可以直接點query查看
方式2:配置文件固定配置
適用面更廣 只要執(zhí)行了orm操作 都會打印內(nèi)部SQL語句
總結(jié)
到此這篇關(guān)于Django的多表查詢操作實戰(zhàn)的文章就介紹到這了,更多相關(guān)Django多表查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用Python連接MySQL超詳細(xì)實戰(zhàn)教程
mysql是關(guān)系型數(shù)據(jù)庫,支持大型的數(shù)據(jù)庫,可以處理擁有上千萬條記錄的大型數(shù)據(jù)庫,這篇文章主要介紹了利用Python連接MySQL的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2026-02-02
將圖片文件嵌入到wxpython代碼中的實現(xiàn)方法
前面一篇文章中提到的那個程序,GUI中包含了一張圖片。在編譯成exe文件發(fā)布時,無法直接生成一個單獨的exe文件。因此需要直接把圖片寫入到代碼中2014-08-08
python統(tǒng)計一個文本中重復(fù)行數(shù)的方法
這篇文章主要介紹了python統(tǒng)計一個文本中重復(fù)行數(shù)的方法,涉及針對Python中dict對象的使用及相關(guān)本文的操作,具有一定的借鑒價值,需要的朋友可以參考下2014-11-11

