Django--orm的其他操作

Django-orm的一些骚操作

https://www.cnblogs.com/liuqingzheng/articles/17858161.html

1 django的orm支持原生sql

##### row方法  常用

ret = Author.objects.raw('select * from app01_author where nid>1')
# 常规写法: 原生sql查询的表,放进对应orm表的对象    eg: author表的字段 与 Author对象 


ret = Author.objects.raw('select * from app01_book where nid>1')
# 强大之处:原生sql查询的表,放进对应orm有关联表的对象  eg: book表的字段 与 Author对象 
# 好处:有相应的字段的数据会留下  eg:name       没有对应的字段会舍弃  eg: price   


##### connection方法

from django.db import connection, connections
# 需要配置数据库
# cursor=connection['default'].cursor() 
cursor = connection.cursor()  
# 不传参数的情况
cursor.execute("""select  * from epos_cookbook""")

# 为原生sql语句设置参数的情况
# cursor.execute("""select  * from  epos_cookbook   where   id=%s""",[2,]) # 2 是 id
# cursor.execute("""select  * from  api_userinfo   where   id=%s"""%1)

# 防止注入攻击
cursor.execute("select  * from  epos_cookbook   where   id=%s", params=[1, ])
# row=cursor.fetchone()
# row=cursor.fetchmany()
row = cursor.fetchall()  ##拿到全部的数据

print(row)

2 反向生成models

# django中如何反向生成models   从表映射到orm的models
python manage.py inspectdb > app/models.py

3 同步数据的命令

# 正常迁移数据
  模型表中新增字段---》两条命令---》同步到数据中

# 骚操作
  模型表中新增字段---》不要了---》在数据中增加字段
    
  # 不执行迁移命令,models 和 表字段  相对应上就行
  # 但 以后都不执行,不然会出错   因为没有迁移记录
posted @ 2022-08-10 12:02  Edmond辉仔  阅读(37)  评论(0)    收藏  举报