Django中使用原生SQL

我只是一个虾纸丫 提交于 2020-03-04 17:34:06
  1. 使用extra:结果集修改器,一种提供额外查询参数的机制

    models.Book.objects.filter(publisher__name='人民出版社').extra(where=['price>50'])
    models.Book.objects.filter(publisher__name='人民出版社', price__gt=50)
    
    models.Book.objects.extra(select={'count': 'select count(*) from hello_Book'})
  2. 使用raw:执行原始sql并返回模型实例

    Book.objects.raw('select * from hello_Book')  # 返回模型实例
  3. 执行自定义SQL语言:connection

    from django.db import connection
    
    cursor=connection.cursor()
    
    # 插入操作
    cursor.execute("insert into hello_author(name) values('钱钟书')")
    
    # 更新操作
    cursor.execute("update hello_author set name='abc' where name='bcd'")
    
    # 删除操作
    cursor.execute("delete from hello_author where name='abc'")
    
    # 查询操作
    cursor.execute("select * from hello_author")
    
    raw=cursor.fetchone()  # 返回结果行游标直读向前,读取一条
    cursor.fetchall()  # 从游标位置开始,读取所有
  1. 使用extra:结果集修改器,一种提供额外查询参数的机制

    models.Book.objects.filter(publisher__name='人民出版社').extra(where=['price>50'])
    models.Book.objects.filter(publisher__name='人民出版社', price__gt=50)
    
    models.Book.objects.extra(select={'count': 'select count(*) from hello_Book'})
  2. 使用raw:执行原始sql并返回模型实例

    Book.objects.raw('select * from hello_Book')  # 返回模型实例
  3. 执行自定义SQL语言:connection

    from django.db import connection
    
    cursor=connection.cursor()
    
    # 插入操作
    cursor.execute("insert into hello_author(name) values('钱钟书')")
    
    # 更新操作
    cursor.execute("update hello_author set name='abc' where name='bcd'")
    
    # 删除操作
    cursor.execute("delete from hello_author where name='abc'")
    
    # 查询操作
    cursor.execute("select * from hello_author")
    
    raw=cursor.fetchone()  # 返回结果行游标直读向前,读取一条
    cursor.fetchall()  # 从游标位置开始,读取所有
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!