再次学习Django,实现sql的页面显示及条件查询
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.shortcuts import render_to_response from django.db import connection from django.shortcuts import render from django.views.decorators import csrf cursor = connection.cursor() # 表单 def pagesprofile_form(request): return render_to_response('pages-profile.html') # 接收请求数据 def pagesprofile(request): request.encoding = 'utf-8' if 'q' in request.GET: message = '你搜索的内容为: ' + request.GET['q'] cursor.execute('select * from testdj_test') sql = cursor.fetchall() # 读取所有 else: message = '你提交了空表单' return HttpResponse(sql) def dictfetchall(cursor): "将游标返回的结果保存到一个字典对象中" desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] def ReturnInfo(cursor): SqlDomain = cursor.description DomainNum = len(SqlDomain) SqlDomainName = [None] * DomainNum for i in range(DomainNum): SqlDomainName[i] = SqlDomain [i][0] return SqlDomainName # 接收POST请求数据 def search_post(request): global ctx_2 cursor.execute('select * from testdj_test') #ctx = {} ctx_2 = dictfetchall(cursor) ctx = ReturnInfo(cursor) return render(request, "post.html", {'results': ctx, 'results_2': ctx_2})
html
<table class="table"> <thead> <tr> {% for title in results%} <td>{{title}}</td> {% endfor%} </tr> </thead> <tbody> {% for item in results_2 %} <tr> {% for context in item.values %} <td>{{context}}</td> {%endfor%} </tr> </tbody> {%endfor%}
实现分页的实例:https://www.jianshu.com/p/332406309476
Sql = "select * from %s where %s=%s" % (self.table, akey, avalue)