Django执行原生SQL
增加额外查询
extra是Django提供的额外接口,可以用来执行额外的查询
在已查到的表中查询
查询固定格式的日期
models.Article.objects.extra(select={'ym':'date_format(create_time,"%%Y-%%m")'}).values('ym')
<QuerySet [{'ym': '2018-02'}, {'ym': '2018-02'}, {'ym': '2018-02'}, {'ym': '2018-01'}]>
查询其他表

上面的ORM查询等效于

额外查询的条件参数要放在select_params中
![]()
完全使用SQL语句
# from django.db import connection, connections # 获取连接
# cursor = connection.cursor() # cursor = connections['default'].cursor() # 获取光标
# cursor.execute("""SELECT * from auth_user where id = %s""", [1]) # 执行sql语句
# row = cursor.fetchone() # 获取单条数据,类似pymysql

浙公网安备 33010602011771号