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
实例二


 

原文地址:https://www.cnblogs.com/xiangtingshen/p/10620759.html