django raw sql查询(原始sql查询)

方法1: 使用 objects.raw()

blog_entity=BlogIndex.objects.raw('select * from myApp_blog where BlogName = %s',['Journey to the West'])
for b in blog_entity:
        print b
        pass

注意 这里 的查询最后会返回一个 Entity的实体, 并且是经过映射好的. 但是 要求 在查询的字段里必须要有 主键.

(例如,我只想select ‘blogname’ 那么 是不行的) 必须加上 blog_id

方法2: 使用 游标

from django.db import transaction
from django.db import connection
from django.db import connections

cursor = connection.cursor()
#从其他数据库 在多数据库的时候需要

#cursor = connections['my_db_alias'].cursor()

cursor.execute('select * from myApp_blog WHERE  blog_name=%s',['name'])
row=cursor.fetchone() #只读取一行
rows=cursor.fetchall() #读取所有行
cursor.execute('delete FROM app_blog where  blog_name=%s',['name'])
transaction.commit()

#设置自动提交事务 官方推荐 不再需要 手动执行 commit
#@transaction.atomic
#@transaction.non_atomic_requests

def idx(request):
    cursor = connection.cursor()
    cursor.execute('delete FROM app_blog where  blog_name=%s',['name'])
    pass
留言:

称呼:*

邮件:

网站:

内容: