zoukankan      html  css  js  c++  java
  • Django中执行原生SQL语句【新编辑】

    参考我的个人博客

    这部分迁移到了个人博客中:Django中执行原生SQL语句

    这里需要补充一下,还有一个extra方法:

    ret = models.Student.objects.all().extra(where=['id > %s'], params=['1'], order_by=['-id'])
    # print(ret)
    # for i in ret:
    #     print(i)

     小结

    extra

    Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))
    Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
    Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
    Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])

    raw

    # 执行原生SQL
    models.UserInfo.objects.raw('select * from userinfo')
    
    # 如果SQL是其他表时,必须将名字设置为当前UserInfo对象的主键列名
    models.UserInfo.objects.raw('select id as nid from 其他表')
    
    # 为原生SQL设置参数
    models.UserInfo.objects.raw('select id as nid from userinfo where nid>%s', params=[12,])
    
    name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
    Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)

    直接执行原生SQL

    from django.db import connection, connections
    cursor = connection.cursor()  # cursor = connections['default'].cursor()
    cursor.execute("""SELECT * from auth_user where id = %s""", [1])
    row = cursor.fetchone() # fetchall()/fetchmany(..)

    选择数据库 

    queryset = models.Course.objects.using('default').all()

    ~~

  • 相关阅读:
    修改spring boot 启动logo
    查看jvm常用命令
    intellij IDEA破解
    hdu 新生晚会
    How many prime numbers(素数)
    2077 汉诺塔IV
    Factorial
    双人黑白块
    EasyX
    七夕情人节
  • 原文地址:https://www.cnblogs.com/paulwhw/p/8613655.html
Copyright © 2011-2022 走看看