一、原生sql
# 原生sql(有些sql用orm写不出来)
# 两种方案
# 第一种:用的比较少
# from django.db import connection
#
# cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)
#
# cursor.execute("""SELECT * from app01_book where id = %s""", [1])
#
# # row = cursor.fetchone()
# row = cursor.fetchall()
# print(row)
# 第二种,用的多
# books=models.Book.objects.raw('select * from app01_book where id >3')
# print(books)#RawQuerySet对象
# for book in books:
# print(book.name)
# books=models.Book.objects.raw('select * from app01_publish')
# for book in books:
# print(book.__dict__)
# print(book.name)
# print(book.addr)
# print(book.email)
# print(book.price)
# authors = models.Author.objects.raw('SELECT app01_author.id,app01_author. NAME,app01_authordetail.sex FROM app01_author JOIN app01_authordetail ON app01_author.author_detail_id = app01_authordetail.id WHERE app01_authordetail.sex = 1')
#
# for author in authors:
# print(author.name)
# print(author.__dict__)
二、事务(请求,装饰器,局部)
# 事物:ACID,事物的隔离级别(搜),锁, 行级锁,表级锁
# djanog orm中使用事物:原子性操作,要么都成功,要么都失败
# 新增一个作者详情,新增一个作者
# 事物的三个粒度
# 1 局部使用
from django.db import transaction
with transaction.atomic(): # 都在事物中,要么都成功,要么都失败
author_detail=models.AuthorDetail.objects.create(addr='xxx',phone='123',sex=1)
# raise Exception('抛了异常')
author=models.Author.objects.create(name='llqz',age=19,author_detail=author_detail)
# 2 视图函数装饰器,这一个视图函数都在一个事物中
# @transaction.atomic
# def index(request):
# return HttpResponse('ok')
# 3 整个http请求,在事物中,在setting.py中配置
'''
DATABASES = {
'default': {
...
'PORT': 3306,
'ATOMIC_REQUEST': True,
}
}
'ATOMIC_REQUEST': True,
设置为True统一个http请求对应的所有sql都放在一个事务中执行(要么所有都成功,要么所有都失败)。
'''