开发者社区 问答 正文

django中怎么写原生SQL

django中怎么写原生SQL

展开
收起
珍宝珠 2019-11-20 14:39:18 2558 分享 版权
1 条回答
写回答
取消 提交回答
  • 使用extra:

    查询人民邮电出版社出版并且价格大于50元的书籍
    
    Book.objects.filter(publisher__name='人民邮电出版社').extra(where=['price>50'])
    
    

    使用raw

    books=Book.objects.raw('select * from hello_book')
    for book in books:
        print book
    
    

    自定义sql

    from django.db import connection
     
    cursor = connection.cursor()
    cursor.execute("insert into hello_author(name) VALUES ('郭敬明')")
    cursor.execute("update hello_author set name='韩寒' WHERE name='郭敬明'")
    cursor.execute("delete from hello_author where name='韩寒'")
    cursor.execute("select * from hello_author")
    cursor.fetchone()
    cursor.fetchall()
    
    2019-11-20 14:40:37
    赞同 展开评论
问答分类:
问答地址: