數據庫同步
- 相關命令
flush // 清空數據庫,數據表還在
makemigrations, migrate
sqlflush, sqlmigrate // 查看相關命令的對應數據庫腳本
- 無法同步數據庫終極大招:
刪除 migrations 目錄下所有文件(init.py 除外),刪除數據庫,然后重新創建數據庫,再同步數據庫
常用 ORM 操作(python manage.py shell)
- 新增 (create, save) :關系的插入可以選擇 id 的方式,或者 object 的方式
1, 增加一個作者
author = Author.objects.create(name='張三')
2,增加作者詳細信息
AuthorDetail.objects.create(sex=False, email='jinyong@123.com', address='臺灣', birthday='1982-04-17', author_id=1)
3,save方式
pub = Publisher()
pub.name = '出版社'
pub.save()
book = Book.objects().create(publisher=pub) // 外健
book.authors.add(author) // 多對多
- 更新(update, save)
author.name = '葉良辰'
author.save()
Author.objects.filter(id=1).update(name='張非') // 此處不可以用 get
- 查詢(惰性機制)
Author.objects.all()
- 刪除(delete :同樣是 objects 的方法)
Author.objects.filter(id=1).delete() // 默認級聯刪除
官方文檔:
https://docs.djangoproject.com/en/1.11/ref/models/querysets/
QuerySet 查詢 API
- 特點: 1,迭代,2,切片
- 常用API
get() // 返回 model, 查不到會拋異常
all(), filter(), exclude(), order_by(), reverse(), distinct(), values(), values_list()
# values()
以 KEY:VALUE 的形式返回所選擇的字段組成的數據集
# values_list()
只以 VALUE 的形式返回所選擇的字段組成的數據集
count(), first(), last(), exists()
實例:
1,id為1 的書籍信息,只顯示名稱和出版日期
Book.objects.filter(id=1).values('name','publisher_date')
2,
Publisher.objects.all().order_by('id').reverse()
3,
Publisher.objects.values_list('city').distinct()
4,
Publisher.objects.filter(city='北京')
5,
Author.objects.filter(sex='男').count()
- 強大的 Field lookups 比如:( 用于 filter() , get() )
...
Entry.objects.get(headline__icontains='Lennon')
Entry.objects.filter(id__in=[1, 3, 4])
Entry.objects.filter(headline__startswith='Lennon')
# 以下功能需要 DateTimeField
Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
Entry.objects.filter(pub_date__isnull=True)
Entry.objects.get(title__regex=r'^(An?|The) +')
...
多表查詢
- 例子
1,一對一關聯
AuthorDetail.objects.values('name', 'auhor__detail')
2,多對多關聯
Book.objects.filter(name='name').values('authors__name', 'publisher_name')
3,
Book.objects.filter(author__name='胡大海')
4,
Book.objects.filter(publisher__name='廣東')
5,
Book.objects.filter(publisher__name='廣東').values('authors__name').distinct()
- _set :用于主鍵類訪問外鍵類
book.authors_set.all() // 錯誤, 因為有定義 authors 字段
author.book_set.all() // 正確
聚合及分組 (aggregate, annotate)
- 例子
# 聚合函數 django.db.models
Count(), Avg(), Max(), Min(), Sum()
1,
Book.objects.filter(name='廣東').aggregate(Count('name'))
2,
Book.objects.filter(authors__name='胡').aggregate(Sum('price'))
3,分組
Book.objects.values('author__name').annotate(Sum('price'))
4,
Book.objects.values('publisher__name').annotate(Min('price'))
原生 sql
- extra
Book.objects.filter().extra(where=['price > 50'])
Book.objects.extra(select={'count':'select count(*) from hello_book'})
- raw
Book.objects.raw('select * from hello_book')
- 不依賴 model 的 sql
from django.db import connection
cur = connection.cursor
cur.execute()
raw = cur.fetchone
res = cur.fetchall