zoukankan      html  css  js  c++  java
  • Django框架操作数据库的两种方式

    Django操作数据库的前提操作是成功连接数据库,详情见上篇:https://www.cnblogs.com/kristin/p/10791358.html

    • Django查询数据库的方式一
    from django.db import connection
    from django.http import HttpResponse
    def research(request):
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM `user` WHERE `status` = '3' AND `created` <= '1557331200' AND `finished` >= '1557417599'")
        sql = cursor.fetchall()
        return HttpResponse(sql)
        
    # shell模式打印输出结果的类型,print(type(sql)),结果为<class 'tuple'>  
    
    • Django查询数据库的方式二
    from django.db import connection
    from quicktool.models import User
    from django.http import HttpResponse
    def research(request):
        sql = User.objects.all().filter(status=3).filter(created__lte=1557331200).filter(finished__gte=1557417599).values_list()
        #或sql = User.objects.all().filter(status=3).filter(created__lte=1557331200).filter(finished__gte=1557417599).values()
        return HttpResponse(sql)
        
    # values_list()迭代时返回元组tuple;values()迭代时返回字典dict
    

      

    上述两种方式查询的sql语句是一致的:

    注:QuerySet对象可用.query.__str__()或 .query属性打印执行的sql语句

    sql = User.objects.all().filter(status=3).filter(created__lte=1557331200).filter(finished__gte=1557417599)
    cursor.execute("SELECT * FROM `user` WHERE `status` = '3' AND `created` <= '1557331200' AND `finished` >= '1557417599' ")
    

      

  • 相关阅读:
    esp8266(3) Arduino通过ESP8266连接和获取网站源代码
    esp8266(2) 智能配置
    图像工程考试
    Arduino IDE for ESP8266 ()esp8266项目 WIFI攻击器
    esp8266(1) 手机+Arduino+esp8266通信
    esp8266(0) AT指令
    ROS ZED
    手机APP
    Arduino IDE for ESP8266教程(0)配置IDE
    Arduino 433 + 串口
  • 原文地址:https://www.cnblogs.com/kristin/p/10984798.html
Copyright © 2011-2022 走看看