Django基礎(三)

 

#models.py
from django.db import models

class Book(models.Model):
    nid=models.AutoField(primary_key=True)
    title=models.CharField(max_length=32)
    pubDate=models.DateField()
    price=models.DecimalField(max_digits=6,decimal_places=2)
    read_num=models.IntegerField(default=0)
    comment_num=models.IntegerField(default=0)
    
    #書籍與出版社:一對多
    publisher=models.ForeignKey('Publish', related_name='bookList')

    #書籍與做者:多對多
    authors=models.ManyToManyField('Author')

    def __str__(self):
        return self.title

class Publish(models.Model):
    name=models.CharField(max_length=32)
    addr=models.CharField(max_length=32)
    tel=models.BigIntegerField()

    def __str__(self):
        return self.name

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

    def __str__(self):
        return self.name

class AuthorDetail(models.Model):
    addr=models.CharField(max_length=32)
    author=models.OneToOneField('Author')

#生成的第三張表的表名是 app01_book_authors,可是咱們不能直接操做這張表

ORM跨表添加python

1.一對多添加git

1.publish_obj=Publish.objects.get(id=2)
表.objects.create(title='python',publisher=publish_obj)
2.表.objects.create(title='python',publisher_id=2)

2.多對多添加django

authors=models.ManyToManyField('Author')  #與這本書關聯的做者對象集合

book_obj=models.Book.objects.create(title=title,pubDate=pubdate,price=price,publisher_id=publish_id)

#方式1
print(book_obj.authors.all())  #QuerySet  []
alex=models.Author.objects.get(name='alex')
egon=models.Author.objects.get(name='egon')
#綁定關係
book_obj.authors.add(alex,egon)   
print(book_obj.authors.all())  #QuerySet  [author_alex,author_egon]
#方式2
author_list=models.Author.objects.all()
book_obj.authors.add(*author_list)

#解除關係
book_obj=models.Book.objects.get(nid=14)
print(book_obj.authors.all())
alex=models.Author.objects.get(name='alex')
book_obj.authors.remove(alex)

author_list=models.Author.objects.filter(id__gt=1)
book_obj.authors.remove(*author_list)

#清空
book_obj.authors.clear()

ORM跨表查詢app

1.基於對象的跨表查詢函數

正向查詢按字段,反向查詢按表名(小寫)_setspa

一對多跨表查詢 1.查詢python這本書出版社的地址
book_obj=Book.objects.get(title=python)
book_obj.publisher.addr
多對多跨表查詢 1.查詢python這本書的全部做者的姓名和年齡

book_python=models.Book.objects.get(title='python')
author_list=book_python.authors.all()
for author in author_list:
    print(author.name,author.age)


book_python=models.Book.objects.filter(title='python')
for book_python in book_pythons:
    author_list=book_python.authors.all()
    for author in author_list:
        print(author.name,author.age)
1.查詢人民出版社出版過的書籍名稱及價格

pub_obj=models.Publish.objects.get(name='renmin')
book_list=pub_obj.book_set.all() 或 book_list=pub_obj.bookList.all() #Query  與這個出版社關聯的全部書籍對象

for obj in book_list:
    print(obj.title,obj.price)


2.alex出版過的全部書籍的名稱

alex=models.Author.objects.get(name='alex')
book_list=alex.book_set.all()
for book in book_list:
    print(book.title,book.price)
一對一正向查詢

查詢addr在沙河的做者
authorDetail=models.AuthorDetail.objects.get(addr='shahe')
print(authorDetail.author.name)


一對一反向查詢:按表名(小寫),不須要加_set

查詢alex在哪裏
alex=models.Author.objects.get(name='alex')
alex.authordetail.addr

2.基於雙下劃線的跨表查詢code

正向查詢按字段,反向查詢按關聯的表名對象

#查詢python這本書的價格
ret=models.Book.objects.filter(title='python').values('price','title')
print(ret)
#查詢python這本書出版社的地址和名稱

正向查詢:按字段
ret2=models.Book.objects.filter(title='python').values_list('publisher__name','publisher__addr')
print(ret2)
反向查詢:按表名
ret3=models.Publish.objects.filter(bookList__title='python').values_list('name','addr')
print(ret3)
#查詢人民出版社出版過的全部書籍名稱和價格
models.Book.objects.filter(publisher__name='renmin').values('title','price')

models.Publish.objects.filter(name='renmin').values('bookList__name','bookList_price')
#查詢egon出版過的全部書籍的名字(多對多)
models.Author.objects.filter(name='egon').values('book__title')

models.Book.objects.filter(authors__name='egon').values('title')
#地址以沙河開頭的做者出版過的全部書籍名稱以及出版社名稱
ret=models.Book.objects.filter(authors__authordetail__addr__startswith='sha').values('title','publisher__name')
print(ret.count())

聚合與分組blog

1.聚合函數 SUM AVG MIN MAX COUNT
2.聚合函數能夠單獨使用,不必定要和分組配合使用;只不過聚合函數與group by搭配ci

aggregate()

#單純聚合函數
#計算全部圖書的平均價格
from django.db.models import Avg,Count,Sum,Min,Max

models.Book.objects.all().aggregate(Avg('price')) 

annotate()  返回queryset

爲QuerySet重的每個對象都生成一個獨立的彙總值
#統計每一本書的做者個數
ret=models.Book.objects.all().annotate(auathors_num=Count('authors'))
for obj in ret:
    print(obj.nid,obj.title,obj.author_num)


#查詢每個出版社出版過的全部書籍的總價格
ret=models.Publish.objects.all().annotate(priceSum=Sum('bookList__price'))
for obj in ret:
    print(obj.id,obj.name,obj.priceSum)
或
ret=models.Book.objects.all().values('publisher__name').annotate(priceSum=Sum('price')).values('publisher__name','priceSum')

F查詢與Q查詢

from django.db.models import F,Q

ret1=models.Book.objects.filter(comment_num__gt=50)
ret2=models.Book.objects.filter(comment_num__gt=F('read_num'))
#評論數大於2倍閱讀數的文章
ret3=models.Book.objects.filter(comment_num__gt=F('read_num')*2)
#給每本書漲價10元
models.Book.objects.all().update(F('price')+10)
#查詢評論數大於500或閱讀數也大於50而且價格低於100
models.Book.objects.filter((Q(comment_num__gt=50)|Q(read_num__gt=50))&Q(price__lt=100))
相關文章
相關標籤/搜索