如下所示:
node2:/django/mysite/blog#cat views.py 1, # -*- coding: utf-8 -*- from __future__ import unicode_literals # from django.shortcuts import render, render_to_response from .models import * # Create your views here. from django.http import HttpResponse from django.template import loader import MySQLdb def query(): conn= MySQLdb.connect( host='localhost', port = 3306, user='root', passwd='1234567', db ='tlcb', ) cur = conn.cursor() a=cur.execute("select title,body, DATE_FORMAT(timestamp,'%Y~%m~%d %k.%i.%s') A from blog_blogpost") info = cur.fetchall() return info cur.close() conn.close() def archive(req): print 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' print req print type(req) print req.GET print '#############################' print req.GET['aa'] print req.GET['cc'] print '#############################' print 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' # get all blogpost objects posts =query() print posts print type(posts) #print blog_list template = loader.get_template('archive.html') context = { 'posts':posts } print '------------------------------------------' print HttpResponse(template.render(context, req)) print '------------------------------------------' return HttpResponse(template.render(context, req)) node2:/django/mysite/blog# node2:/django/mysite/blog/templates#vi archive.html node2:/django/mysite/blog/templates# node2:/django/mysite/blog/templates# node2:/django/mysite/blog/templates# node2:/django/mysite/blog/templates#cat archive.html {% extends "base.html" %} {% block content %} {% for post in posts %}{{ post.0 }}
{{ post.1 | date:"1,F jS"}}
{{ post.2 }}
{% endfor %} {% endblock %} (('dd', 'ddd', '2017~11~24 8.31.42'), ('66666666', '66666', '2017~11~24 8.35.25'), ('777777777', '77777777777', '2017~11~27 1.46.15'))在自定义 model 方法和模块级方法里,你可以自由的执行自定义SQL语句. 对象 django.db.connection 表示当前的数据库连接. 调用connection.cursor() 得到一个游标对象. 然后调用 cursor.execute(sql, [params])``以执行 SQL 语句, 使用 ``cursor.fetchone() 或cursor.fetchall() 得到结果集. 下面是一个例子: def my_custom_sql(self): from django.db import connection cursor = connection.cursor() cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) row = cursor.fetchone() return row 如果你的SQL语句改变了数据库中的数据 -- 比如你使用了 DELETE 或 UPDATE 语句. 你需要调用 connection.commit() 来使你的修改生效. 例子: def my_custom_sql2(self): from django.db import connection cursor = connection.cursor() cursor.execute("DELETE FROM bar WHERE baz = %s", [self.baz]) connection.commit()
以上这篇python django 原生sql 获取数据的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。