django(八)之數據庫表的一對多,多對多表-增刪改查


 

單表操作

        表記錄的添加
             
            方式一:
            Book()
            b=Book(name="python基礎",price=99,author="yuan",pub_date="2017-12-12")
            b.save()
            方式二:
            Book.objects.create()
            Book.objects.create(name="老男孩linux",price=78,author="oldboy",pub_date="2016-12-12")


        表記錄的修改
            方式一:
            
            b=Book.objects.get(author="oldboy")
            b.price=120
            b.save()
            
            方式二:
            #update是QuerySet
            Book.objects.filter(author="yuan").update(price=999)
         
        表記錄的刪除:
            Book.objects.filter(author="oldboy").delete()
            
        表記錄的查詢(重點):
        
                book_list = Book.objects.filter(id=2)
                book_list=Book.objects.exclude(author="yuan").values("name","price")
                
                book_list=Book.objects.all()
                book_list = Book.objects.all()[::2]
                book_list = Book.objects.all()[::-1]
                
                #first,last,get取到的是一個實例對象,並非一個QuerySet的集合對象
                book_list = Book.objects.first()
                book_list = Book.objects.last()  
                book_list = Book.objects.get(id=2)#只能取出一條記錄時才不報錯
                
                
                ret1=Book.objects.filter(author="oldboy").values("name")
                ret2=Book.objects.filter(author="yuan").values_list("name","price")
                
               

                book_list= Book.objects.all().values("name").distinct()
                book_count= Book.objects.all().values("name").distinct().count()
               
            
                模糊查詢  雙下划線__

                book_list=Book.objects.filter(name__icontains="P").values_list("name","price")
                book_list=Book.objects.filter(id__gt=5).values_list("name","price")
                
 
      多表操作(一對多):
               #添加記錄
               #publish_id=2
               Book.objects.create(name="linux運維",price=77,pub_date="2017-12-12",publish_id=2)
               

               #publish=object
               Book.objects.create(name="GO",price=23,pub_date="2017-05-12",publish=publish_obj)
               
               #查詢記錄(通過對象)
               
                     正向查詢:
                     book_obj=Book.objects.get(name="python")   
                     pub_obj=book_obj.publish----》書籍對象對應的出版社對象
                     pub_obj.name
                     反向查詢:
                     pub_obj = Publish.objects.filter(name="人民出版社")[0]
                     pub_obj.book_set.all().values("name","price")
                     
               #查詢記錄(filter values  雙下划線__)
                     
                    #人民出版社出版過的書籍與價格
                    ret=Book.objects.filter(publish__name="人民出版社").values("name","price")
                    
                    #python這本書出版社的名字
                    ret2=Publish.objects.filter(book__name="python").values("name")
                    
                    #python這本書出版社的名字
                    ret3=Book.objects.filter(name="python").values("publish__name")
                    
                    #北京的出版社出版書的名字
                    ret4=Book.objects.filter(publish__city="北京").values("name")
                    
                    #2017年上半年出版過書的出版社的名字
                    ret5=Book.objects.filter(pub_date__lt="2017-07-01",pub_date__gt="2017-01-01").values("publish__name")
                    
                    
     多表操作(多對多): 
                     
                    創建多對多的關系 author= models.ManyToManyField("Author")(推薦)
                    
                    
                    書籍對象它的所有關聯作者  obj=book_obj.authors.all()
                            綁定多對多的關系  obj.add(*QuerySet)   
                                              obj.remove(author_obj)
                                              
                                              
                    如果想向第三張表插入值的方式綁定關系:  手動創建第三張表

                            # class Book_Author(models.Model):
                            #     book=models.ForeignKey("Book")
                            #     author=models.ForeignKey("Author")                    
                            Book_Author.objects.create(book_id=2,author_id=3)
                            
                    
                    掌握:通過 filter values (雙下換線)進行多對多的關聯查詢(形式和一對多) 

 

models.py

from django.db import models

# Create your models here.
class Book(models.Model):
    name=models.CharField(max_length=20)
    price=models.IntegerField()
    pub_date=models.DateField()
    publish=models.ForeignKey("Publish")
    authors=models.ManyToManyField("Author")
    def __str__(self):
        return self.title

class Publish(models.Model):
    name=models.CharField(max_length=32)
    city=models.CharField(max_length=32)
    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField(default=20)

    def __str__(self):
        return self.name
models.py

 

ManyToManyField字段會自動幫我們創建一張表,book_author
Book.objects.create(name='linux',price=68,pub_date='2018-11-18',publish_id='1',authors=2)
將會報錯:
Direct assignment to the forward side of a many-to-many set is prohibited. Use authors.set() instead.
我們也可以自己創建第三第三張表,將MangToManyField去掉

from django.db import models

# Create your models here.

class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.IntegerField()
    pub_date = models.DateField()
    publish = models.ForeignKey("Publish",on_delete=models.CASCADE)
    # authors = models.ManyToManyField("Author")

    def __str__(self):
        return self.name

class Publish(models.Model):
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()

    def __str__(self):
        return self.name

class Book_Author(models.Model):
    book = models.ForeignKey("Book", on_delete=models.CASCADE)
    author = models.ForeignKey("Author", on_delete=models.CASCADE)
第三張表

 

 

解決TypeError: __init__() missing 1 required positional argument: 'on_delete'

試用Djiango的時候發現執行mange.py makemigrations 和 migrate是會報錯,少位置參數on_delete,查了一下是因為指定外鍵的方式不對,改一下就OK了。

即在外鍵值的后面加上 on_delete=models.CASCADE

原因:

在django2.0后,定義外鍵和一對一關系的時候需要加on_delete選項,此參數為了避免兩個表里的數據不一致問題,不然會報錯:
TypeError: __init__() missing 1 required positional argument: 'on_delete'
舉例說明:
user=models.OneToOneField(User)
owner=models.ForeignKey(UserProfile)
需要改成:
user=models.OneToOneField(User,on_delete=models.CASCADE) --在老版本這個參數(models.CASCADE)是默認值
owner=models.ForeignKey(UserProfile,on_delete=models.CASCADE) --在老版本這個參數(models.CASCADE)是默認值
參數說明:
on_delete有CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()五個可選擇的值
CASCADE:此值設置,是級聯刪除。
PROTECT:此值設置,是會報完整性錯誤。
SET_NULL:此值設置,會把外鍵設置為null,前提是允許為null。
SET_DEFAULT:此值設置,會把設置為外鍵的默認值。
SET():此值設置,會調用外面的值,可以是一個函數。
一般情況下使用CASCADE就可以了。

 

    ret1 = Book.objects.filter(authors__name='alex').values('name','price')
    ret2 = Book.objects.filter(authors__name='alex').values_list('name', 'price')
    print(ret1)
    print(ret2)

'''
<QuerySet [{'name': 'linux', 'price': 68}, {'name': 'python', 'price': 78}, {'name': 'java', 'price': 88}]>
<QuerySet [('linux', 68), ('python', 78), ('java', 88)]>

'''
values與values_list

 

---------->聚合查詢和分組查詢

<1> aggregate(*args,**kwargs):

   通過對QuerySet進行計算,返回一個聚合值的字典。aggregate()中每一個參數都指定一個包含在字典中的返回值。即在查詢集上生成聚合。

from django.db.models import Avg,Min,Sum,Max

從整個查詢集生成統計值。比如,你想要計算所有在售書的平均價錢。Django的查詢語法提供了一種方式描述所有
圖書的集合。

>>> Book.objects.all().aggregate(Avg('price'))
{'price__avg': 34.35}

aggregate()子句的參數描述了我們想要計算的聚合值,在這個例子中,是Book模型中price字段的平均值

aggregate()是QuerySet 的一個終止子句,意思是說,它返回一個包含一些鍵值對的字典。鍵的名稱是聚合值的
標識符,值是計算出來的聚合值。鍵的名稱是按照字段和聚合函數的名稱自動生成出來的。如果你想要為聚合值指定
一個名稱,可以向聚合子句提供它:
>>> Book.objects.aggregate(average_price=Avg('price'))
{'average_price': 34.35}


如果你也想知道所有圖書價格的最大值和最小值,可以這樣查詢:
>>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
{'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}

 

<2> annotate(*args,**kwargs):

   可以通過計算查詢結果中每一個對象所關聯的對象集合,從而得出總計值(也可以是平均值或總和),即為查詢集的每一項生成聚合。

  查詢alex出的書總價格                   

       

        查詢各個作者出的書的總價格,這里就涉及到分組了,分組條件是authors__name

           

         查詢各個出版社最便宜的書價是多少

       

---------->F查詢和Q查詢

僅僅靠單一的關鍵字參數查詢已經很難滿足查詢要求。此時Django為我們提供了F和Q查詢:

# F 使用查詢條件的值,專門取對象中某列值的操作

    # from django.db.models import F
    # models.Tb1.objects.update(num=F('num')+1)


# Q 構建搜索條件
    from django.db.models import Q

    #1 Q對象(django.db.models.Q)可以對關鍵字參數進行封裝,從而更好地應用多個查詢
    q1=models.Book.objects.filter(Q(title__startswith='P')).all()
    print(q1)#[<Book: Python>, <Book: Perl>]

    # 2、可以組合使用&,|操作符,當一個操作符是用於兩個Q的對象,它產生一個新的Q對象。
    Q(title__startswith='P') | Q(title__startswith='J')

    # 3、Q對象可以用~操作符放在前面表示否定,也可允許否定與不否定形式的組合
    Q(title__startswith='P') | ~Q(pub_date__year=2005)

    # 4、應用范圍:

    # Each lookup function that takes keyword-arguments (e.g. filter(),
    #  exclude(), get()) can also be passed one or more Q objects as
    # positional (not-named) arguments. If you provide multiple Q object
    # arguments to a lookup function, the arguments will be “AND”ed
    # together. For example:

    Book.objects.get(
        Q(title__startswith='P'),
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
    )

    #sql:
    # SELECT * from polls WHERE question LIKE 'P%'
    #     AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')

    # import datetime
    # e=datetime.date(2005,5,6)  #2005-05-06

    # 5、Q對象可以與關鍵字參數查詢一起使用,不過一定要把Q對象放在關鍵字參數查詢的前面。
    # 正確:
    Book.objects.get(
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
        title__startswith='P')
    # 錯誤:
    Book.objects.get(
        question__startswith='P',
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))

 

from django.shortcuts import render,HttpResponse
from django.db.models import Avg,Min,Sum,Max,Count
from django.db.models import Q,F
# Create your views here.
from app01.models import *

def index(request):


    return render(request,"index.html")

def addbook(request):

    # Book.objects.create(name="linux運維",price=77,pub_date="2017-12-12",publish_id=2)

    #publish_obj=Publish.objects.filter(name="人民出版社")[0]
    #Book.objects.create(name="GO",price=23,pub_date="2017-05-12",publish=publish_obj)

    # book_obj=Book.objects.get(name="python")
    # print(book_obj.name)
    # print(book_obj.pub_date)
    #
    # #一對多:book_obj.publish--------一定是一個對象
    # print(book_obj.publish.name)
    # print(book_obj.publish.city)
    # print(type(book_obj.publish))


    #查詢人民出版社出過的所有書籍名字和價格
    #方式一:
    # pub_obj=Publish.objects.filter(name="人民出版社")[0]
    # ret=Book.objects.filter(publish=pub_obj).values("name","price")
    # print(ret)

    #方式二
    # pub_obj = Publish.objects.filter(name="人民出版社")[0]
    # print(pub_obj.book_set.all().values("name","price"))
    #print(type(pub_obj.book_set.all()))

    #方式三
    # ret=Book.objects.filter(publish__name="人民出版社").values("name","price")
    # print(ret)
    #
    # python這本書出版社的名字
    # ret2=Publish.objects.filter(book__name="python").values("name")
    # print(ret2)
    # ret3=Book.objects.filter(name="python").values("publish__name")
    # print(ret3)
    #
    # ret4=Book.objects.filter(publish__city="北京").values("name")
    # print(ret4)
    #
    # ret5=Book.objects.filter(pub_date__lt="2017-07-01",pub_date__gt="2017-01-01").values("publish__name")
    # print(ret5)

    #通過對象的方式綁定關系


    # book_obj=Book.objects.get(id=3)
    # print(book_obj.authors.all())
    # print(type(book_obj.authors.all()))
    #
    # author_obj=Author.objects.get(id=2)
    # print(author_obj.book_set.all())


    # book_obj=Book.objects.get(id=3)
    # author_objs=Author.objects.all()
    # #book_obj.authors.add(*author_objs)
    # # book_obj.authors.remove(*author_objs)
    # book_obj.authors.remove(4) # 刪除 author id = 4 的那一項



    #創建第三張表
    # Book_Author.objects.create(book_id=2,author_id=2)
    #
    # obj=Book.objects.get(id=2)
    # print(obj.book_author_set.all()[0].author) # 太麻煩

    #alex出過的書籍名稱及價格

    # ret=Book.objects.filter(book_author__author__name="alex").values("name","price") # 第三張表的查詢,太麻煩
    # print(ret)

    # ret2=Book.objects.filter(authors__name="alex").values("name","price","authors__name")
    # print(ret2)

    # ret=Book.objects.all().aggregate(Avg("price"))
    # ret=Book.objects.all().aggregate(Sum("price"))
    # ret=Book.objects.filter(authors__name="alex").aggregate(alex_money=Sum("price"))
    # ret=Book.objects.filter(authors__name="alex").aggregate(Count("price"))
    # print(ret)

    # ret=Book.objects.values("authors__name").annotate(Sum("price"))
    # print(ret)
    # <QuerySet [{'price__sum': 234, 'authors__name': 'alex'}, {'price__sum': 68, 'authors__name': 'xiang'}, 
    # {'price__sum': 98, 'authors__name': 'vincent'}]>

    # 每個出版社最便宜的書
    # ret=Publish.objects.values("name").annotate(abc=Min("book__price"))
    # ret = Book.objects.values("publish__name").annotate(Min('price'))
    # print(ret)
'''
(0.001) SELECT `app_publish`.`name`, MIN(`app_book`.`price`) AS `book__price__min` FROM `app_publish` 
LEFT OUTER JOIN `app_book` ON (`app_publish`.`id` = `app_b
ook`.`publish_id`) GROUP BY `app_publish`.`name` ORDER BY NULL  LIMIT 21; args=()
<QuerySet [{'book__price__min': 68, 'name': '南方出版社'}, {'book__price__min': 88, 'name': '機械出版社'}, 
{'book__price__min': 98, 'name': '人民出版社'}]>

'''

    # b=Book.objects.get(name="GO",price=77)
    # print(b)

    #Book.objects.all().update(price=F("price")+10) 
    # (0.008) UPDATE `app_book` SET `price` = (`app_book`.`price` + 10); args=(10,)


    # ret=Book.objects.filter(Q(name__contains="G"))
    # print(ret)

    # ret=Book.objects.filter(Q(name="GO"),price=87)
    # print(ret)

    #ret=Book.objects.filter(price=200) # 若不適宜結果,sql語句不會執行

    # for i in ret:
    #     print(i.price)
    #
    # Book.objects.all().update(price=200)
    # ret = Book.objects.filter(price=100)
    # for i in ret:
    #     print(i.price)


    # if ret.exists():
    #     print("ok")

    # ret=ret.iterator()
    # print(ret)
    #
    # for i in ret:
    #     print(i.name)
    #
    # for i in ret:
    #     print(i.name)


    return HttpResponse("添加成功")


def update():pass
def delete():pass
def select():pass

 

 

from django.db import models

class Classes(models.Model):
    """
    班級表,男
    """
    titile = models.CharField(max_length=32)
    m = models.ManyToManyField('Teachers',related_name='sssss')

class Teachers(models.Model):
    """
    老師表,女
    """
    name = models.CharField (max_length=32)

class Student(models.Model):
    """
    學生表
    """
    username = models.CharField(max_length=32)
    age = models.IntegerField()
    gender = models.BooleanField()
    cs = models.ForeignKey(Classes,related_name='ssss') # cs,cs_id  1    3班



######################## 單表 ########################
# 增加
# Teachers.objects.create(name='root')
# obj = Teachers(name='root')
# obj.save()
#
# Teachers.objects.all()
# Teachers.objects.filter(id=1)
# Teachers.objects.filter(id=1,name='root')
# result = Teachers.objects.filter(id__gt=1)
# [obj(id,name),]
# result = Teachers.objects.filter(id__gt=1).first()
# 刪除
# Teachers.objects.filter(id=1).delete()
#
# Teachers.objects.all().update(name='alex')
# Teachers.objects.filter(id=1).update(name='alex')

######################## 一對多 ########################
"""
班級:
id    name
 1    3班
 2    6班

學生
id   username    age    gender   cs_id
1      東北       18     男         1
2      東北1      118     男        2
2      東北1      118     男        1
"""
# 增加
# Student.objects.create(username='東北',age=18,gender='男',cs_id=1)
# Student.objects.create(username='東北',age=18,gender='男',cs= Classes.objects.filter(id=1).first() )
# 查看
"""
ret = Student.objects.all()
# []
# [ obj(..),]
# [ obj(1      東北       18     男         1),obj(2      東北1      118     男         2),obj(..),]
for item in ret:
    print(item.id)
    print(item.username)
    print(item.age)
    print(item.gender)
    print(item.cs_id)
    print(item.cs.id)
    print(item.cs.name)
"""
# 刪除
# Student.objects.filter(id=1).delete()
# Student.objects.filter(cs_id=1).delete()

# cid = input('請輸入班級ID')
# Student.objects.filter(cs_id=cid).delete()

# cname = input('請輸入班級名稱')
# Student.objects.filter(cs_id=cid).delete()
# Student.objects.filter(cs__name=cname).delete()




######################## 多對多 ########################

# 多對多
"""
班級:
id  title
1    3班
2    4班
3    5班
老師:
id   title
 1    Alex
 2    老妖
 3    瞎驢
 4    Eric
 老師班級關系表(類):
id   班級id   老師id
 1     1        2
 2     1        3
 4     2        2
 5     2        3
 6     2        4
 7     1        5


# 增
obj = Classes.objects.filter(id=1).first() #1    3班
obj.m.add(2)
obj.m.add([4,3])

# obj = Classes.objects.filter(id=2).first() #1    3班
# obj.m.add(2)
# obj.m.add([4,3])

obj = Classes.objects.filter(id=1).first() #1    3班
# 刪除
# obj.m.remove([4,3])
# 清空
obj.m.clear()
# 重置
obj.m.set([2,3,5])

# 查第三張表
# 把3班的所有老師列舉
obj = Classes.objects.filter(id=1).frist()
obj.id
obj.titile
ret = obj.m.all() # 第三張表
# ret是一個 [ 老師1(id,name),obj(id,name)   ]

"""
實例

 

from django.db import models

班級:
id    name
 1    3班
 2    6班

class School:
    name = models.CharField(max_length=32)
 
 
class Classes(models.Model):
    """
    班級表,男
    """
    titile = models.CharField(max_length=32)
    # m = models.ManyToManyField('Teachers')      # 多對多
    # sch = models.ForeignKey(School)

老師:
id   title
 1    Alex
 2    老妖
 3    瞎驢
 4    Eric
class Teachers(models.Model):
    """
    老師表,女
    """
    name = models.CharField (max_length=32)

學生
id   username    age    gender   cs_id
1      東北       18     男         1
2      東北1      118     男        2
2      東北1      118     男        1
class Student(models.Model):
    """
    學生表
    """
    username = models.CharField(max_length=32)
    age = models.IntegerField()
    gender = models.BooleanField()
    cs = models.ForeignKey(Classes) #
    
    
示例:
    - 所有學生的姓名以及其所在班級名稱,QuerySet
        stu_list = Student.objects.all()
        select * from tb;
        [obj,obj,obj,obj]
        
        stu_list = Student.objects.all().values("id",'username')
        select id,username from tb;
        [{"id":1,'username':'xx'},{id:'',username:''}]   
        
        stu_list = Student.objects.all().values_list("id",'username')
        [(1,'root'), (2,'alex')]
        
        
        stu_list = Student.objects.all().values('username',"cs__name")
        for row in stu_list:
            print(row['username'],row['cs__name'])
        
        stu_list = Student.objects.all().values('username',"cs__titile",“cs__fk__name”)
        
    - 找到3班的所有學生
        Student.objects.filter(cs__name='3班')
        
        obj = Classes.objects.filter(name='3班').first()

    
1. 類代表數據庫表
2. 類的對象代指數據庫的一行記錄
3. FK字段代指關聯表中的一行數據(類的對象)
4. 
    - 正向:fk字段  (*****)
    - 反向:小寫類名_set(默認)   ==> related_name='ssss'

5. 誰是主表?就全部列出其數據
    models.Student.objects.all().values('username', 'cs__titile')
    models.Classes.objects.all().values('titile', 'ssss__username')
    
4. M2M字段,自動生成第三張表;依賴關聯表對第三張表間接操作


對話框添加,刪除,修改:
    添加:
        Ajax偷偷向后台發請求:
            1. 下載引入jQuery
            2. 
                $.ajax({
                    url: '/add_classes.html',
                    type: 'POST',
                    data: {'username':'root','password': '123'},
                    success:function(arg){
                        // 回調函數,arg是服務端返回的數據
                    }
                })
            
作業:
    1.班級管理(排出老師列)
    2.學生管理
    添加,刪除,修改
    3.select標簽 val
實例二


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM