django提供了很方便的数据库操作层,但是有时候你发现它还是不够用。这时候你想直接使用sql操作数据库,django让你很方便使用它,并且提供了2中方式:
a. 基于已创建的model
https://docs.djangoproject.com/en/dev/topics/db/sql/#performing-raw-queries
下面是示例代码:
Blog.objects.raw(“select * from blog_blog”)
<RawQuerySet: ‘select * from blog_blog’>blog = Blog.objects.raw(“select * from blog_blog”)
bg = Blog.objects.raw(“select * from blog_blog”)
bg.count()
Traceback (most recent call last):
File “”, line 1, in
AttributeError: ‘RawQuerySet’ object has no attribute ‘count’len(bg)
Traceback (most recent call last):
File “”, line 1, in
TypeError: object of type ‘RawQuerySet’ has no len()len(list(bg))
9
b. 基于数据库的连接 – 这种方式已经完全脱离了django的model
https://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly
下面是示例代码:
from django.db import connection, transaction
cs = connection.cursor()
bg1 = cs.execute(“select * from blog_blog”)
type(bg1)
<type ‘long’>print bg1
9row = cs.fetchone()
print row
(1L, u’common’, u’my first blog’, u’Jhon’, u’yeah, as you can see from title, this is my first blog. Just for practic’, datetime.date(2012, 4, 20), datetime.date(2012, 4, 20))