如下所示:
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 方法和模塊級(jí)方法里,你可以自由的執(zhí)行自定義SQL語(yǔ)句. 對(duì)象 django.db.connection 表示當(dāng)前的數(shù)據(jù)庫(kù)連接. 調(diào)用connection.cursor() 得到一個(gè)游標(biāo)對(duì)象. 然后調(diào)用 cursor.execute(sql, [params])``以執(zhí)行 SQL 語(yǔ)句, 使用 ``cursor.fetchone() 或cursor.fetchall() 得到結(jié)果集. 下面是一個(gè)例子: 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語(yǔ)句改變了數(shù)據(jù)庫(kù)中的數(shù)據(jù) -- 比如你使用了 DELETE 或 UPDATE 語(yǔ)句. 你需要調(diào)用 connection.commit() 來(lái)使你的修改生效. 例子: 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 獲取數(shù)據(jù)的例子就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
