码迷,mamicode.com
首页 > 其他好文 > 详细

django模型方法extra

时间:2017-09-20 19:25:31      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:self   div   select   turn   book   can   sse   span   last   

## select提供简单数据
# SELECT age, (age > 18) as is_adult FROM myapp_person;
Person.objects.all().extra(select={is_adult: "age > 18"})

## where提供查询条件
# SELECT * FROM myapp_person WHERE first||last ILIKE ‘jeffrey%‘;
Person.objects.all().extra(where=["first||last ILIKE ‘jeffrey%‘"])

## table连接其它表
# SELECT * FROM myapp_book, myapp_person WHERE last = author_last
Book.objects.all().extra(table=[myapp_person], where=[last = author_last])

## params添参数
# !! 错误的方式 !!
first_name = Joe  # 如果first_name中有SQL特定字符就会出现漏洞
Person.objects.all().extra(where=["first = ‘%s‘" % first_name])
# 正确方式
Person.objects.all().extra(where=["first = ‘%s‘"], params=[first_name])

 extra源码

def extra(self, select=None, where=None, params=None, tables=None,
              order_by=None, select_params=None):
        """
        Adds extra SQL fragments to the query.
        """
        assert self.query.can_filter(),                 "Cannot change a query once a slice has been taken"
        clone = self._clone()
        clone.query.add_extra(select, select_params, where, params, tables, order_by)
        return clone

 

django模型方法extra

标签:self   div   select   turn   book   can   sse   span   last   

原文地址:http://www.cnblogs.com/songbird/p/7562923.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!