随笔 - 268,  文章 - 5,  评论 - 8,  阅读 - 26万

[django使用原生SQL的方法](https://www.cnblogs.com/zuichuyouren/p/11094679.html)

# django使用原生SQL的方法

1. 使用extra:

```python
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:

```python
Book.objects.raw('select * from hello_Book') # 返回模型实例
```

3. 执行自定义SQL语言:

```python
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() # 读取所有
```

posted on   root-123  阅读(387)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示