Python框架篇之Django(Models的多表操作)

    技术2022-07-10  107

    一对多

    1、添加记录

    #publish_id=2 Book.objects.create(name="Python进阶",price=77,pub_date="2019-12-12",publish_id=2) #publish=object Book.objects.create(name="GO",price=23,pub_date="2017-05-12",publish=publish_obj)

    2、通过对象查询记录

    #正向查询: 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")

    3、通过filter查询记录(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") #2019年上半年出版过书的出版社的名字 ret5=Book.objects.filter(pub_date__lt="2019-07-01",pub_date__gt="2017-01-01").values("publish__name")

    多对多

    1、创建多对多的关系 author= models.ManyToManyField(“Author”)(推荐)

    2、书籍对象它的所有关联作者 obj=book_obj.authors.all() 绑定多对多的关系 obj.add(*QuerySet) obj.remove(author_obj)

    3、如果想向第三张表插入值的方式绑定关系: 手动创建第三张表

    # class Book_Author(models.Model): # book=models.ForeignKey("Book") # author=models.ForeignKey("Author") Book_Author.objects.create(book_id=2,author_id=3)

    4、练习

    #查询人民出版社出过的所有书籍名字和价格 #方式一: 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())) #方式三:调用publish外键字段 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) #创建第三张表 Book_Author.objects.create(book_id=2,author_id=2) obj=Book.objects.get(id=2) print(obj.book_author_set.all()[0].author)
    Processed: 0.030, SQL: 9