Django 入门教程笔记(二)

数据库同步

  • 相关命令
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='[email protected]', 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

你可能感兴趣的:(Django 入门教程笔记(二))