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' ")