【Django】执行原生SQL查询、.raw()方法执行SQL查询

.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方法查询,如下:

  1. blogs = Blog.objects.filter(caption__icontains = 'python')

        #    filter方法得到的blogs,类型是QuerySet。

用SQL方法查询,如下:

  1. sql = "select * from blog_blog where caption like '%python%'"
  2. blogs = Blog.objects.raw(sql)

       #     这里需要使用raw方法把sql语句转换成Blog对象,此处的blogs类型是RawQuerySet。

简单查询,raw方法执行sql语句要麻烦一些。

下一个查询:根据博客按照评论数倒序排序。

若用QuerySet方法,很复杂,需要用到annotate,并且还有联合Comment对象。至少我自己尝试写了几次都写不出来。

若用SQL方法查询,只需要懂得SQL联合查询和统计即可:

  1. sql = """select blog_blog.* from blog_blog
  2.     left join blog_comment
  3.     on blog_blog.id = blog_comment.blog_id
  4.     group by blog_blog.id
  5.     order by count(blog_comment.id) desc
  6.     """
  7. blogs = Blog.objects.raw(sql)

blog_blog联合blog_comment表,再对blog_comment计数并倒序。

很明显,在复杂查询时,用原始的SQL查询有很明显的优势。

简单查询,用QuerySet方法。复杂查询,用SQL语句的方法。

使用SQL语句查询的raw方法有1个特点:SQL语句中的字段可以包含其他非该模型的字段,一样也会被解析成属性

例如,我按照评论数排序时,也想顺便得到评论数:

  1. sql = """select blog_blog.*, count(blog_comment.id) as comment_num
  2.     from blog_blog
  3.       left join blog_comment
  4.       on blog_blog.id = blog_comment.blog_id
  5.     group by blog_blog.id
  6.     order by count(blog_comment.id) desc
  7.     """
  8. blogs = Blog.objects.raw(sql)

这里的count(blog_comment.id) as comment_num 也会被解析成comment_num属性。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值