.raw()方法的使用:
django中提供了一个raw()方法来使用sql语句进行查询
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField(max_length=50)
Person.objects.raw('SELECT * FROM myapp_person')
# myapp为你的app的名称
1、使用translations将查询到的字段映射到模型字段
name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)
如果你只想要第一条数据,可以这样使用
first_person = Person.objects.raw('SELECT * FROM myapp_person')[0]
first_person = Person.objects.raw('SELECT * FROM myapp_person LIMIT 1')[0]# 当数据库中的数据很多的时候,最好使用第二个方法
2、如果需要执行参数化查询,可以使用下面这个方法
lname = 'Doe'
Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])
3、不使用raw()进行查询
from django.db import connection
def my_custom_sql(self):
with connection.cursor() as cursor:
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
# 如果要在查询中包含文字百分号,则要使用两个%cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' AND id = %s", [id])
例:
Django中模型查询可以用filter和get方法。
虽然有时候可以用__in,__icontains,__year和annotate,aggreg以支持用SQL查询,并且可以返回对应的模型对象。
两个简单的模型:
Blog(博客):id, caption, content
Comment(评论):id, blog_id, comment
注意,id是Django模型的默认字段,无需在创建模型的时候,声明该字段。
简单查询:查询caption标题包含python的Blog。
用filter方法查询,如下:
- blogs = Blog.objects.filter(caption__icontains = 'python')
# filter方法得到的blogs,类型是QuerySet。
用SQL方法查询,如下:
- sql = "select * from blog_blog where caption like '%python%'"
- blogs = Blog.objects.raw(sql)
# 这里需要使用raw方法把sql语句转换成Blog对象,此处的blogs类型是RawQuerySet。
简单查询,raw方法执行sql语句要麻烦一些。
下一个查询:根据博客按照评论数倒序排序。
若用QuerySet方法,很复杂,需要用到annotate,并且还有联合Comment对象。至少我自己尝试写了几次都写不出来。
若用SQL方法查询,只需要懂得SQL联合查询和统计即可:
- sql = """select blog_blog.* from blog_blog
- left join blog_comment
- on blog_blog.id = blog_comment.blog_id
- group by blog_blog.id
- order by count(blog_comment.id) desc
- """
- blogs = Blog.objects.raw(sql)
blog_blog联合blog_comment表,再对blog_comment计数并倒序。
很明显,在复杂查询时,用原始的SQL查询有很明显的优势。
简单查询,用QuerySet方法。复杂查询,用SQL语句的方法。
使用SQL语句查询的raw方法有1个特点:SQL语句中的字段可以包含其他非该模型的字段,一样也会被解析成属性。
例如,我按照评论数排序时,也想顺便得到评论数:
- sql = """select blog_blog.*, count(blog_comment.id) as comment_num
- from blog_blog
- left join blog_comment
- on blog_blog.id = blog_comment.blog_id
- group by blog_blog.id
- order by count(blog_comment.id) desc
- """
- blogs = Blog.objects.raw(sql)
这里的count(blog_comment.id) as comment_num 也会被解析成comment_num属性。