django学习随笔

随笔1:django执行原生sql

单个参数

from django.db import connection

# 获取游标
cursor = connection.cursor()
sql = 'select * from test'
# 执行sql
cursor.execute(sql, )

多个参数

参数为元组

from django.db import connection

# 获取游标
cursor = connection.cursor()
sql = 'select * from test where ds between %s and %s'
args = ('2021-07-09', '2021-08-09')
"""
执行sql
此时执行的sql为:
select * from test where ds between '2021-07-09' and '2021-08-09'
"""
cursor.execute(sql, args)

参数为列表

from django.db import connection

# 获取游标
cursor = connection.cursor()
sql = 'select * from test where ds between %s and %s'
args = ['2021-07-09', '2021-08-09']
"""
执行sql
此时执行的sql为:
select * from test where ds between '2021-07-09' and '2021-08-09'
"""
cursor.execute(sql, args)

参数为字典

from django.db import connection

# 获取游标
cursor = connection.cursor()
sql = 'select * from test where ds between %(start_dt)s and %(end_dt)s'
args = {'start_dt': '2021-07-09', 'end_dt': '2021-08-09'}
"""
执行sql
此时执行的sql为:
select * from test where ds between '2021-07-09' and '2021-08-09'
"""
cursor.execute(sql, args)

那么如何知道执行的sql是怎么样的呢?我在网上找了一圈,没有找到满意的答案,最后查看了pymysql.cursor的源码,发现cursor有个属性叫 _executed,应该就是保存已运行查询的sql的,

print(cursor._executed)

不知道有没有什么更优雅的方式,希望各位大佬不吝赐教。

随笔2: 报错解决

dumpdata报错:CommandError: Unable to serialize database: ‘gbk’ codec can’t encode character ‘\xa0’ in position 1: illegal multibyte sequence

使用 python -Xutf8 manage.py dumpdata XXXXXXX
参考链接:https://stackoverflow.com/questions/64457733/django-dumpdata-fails-on-special-characters

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值