zoukankan      html  css  js  c++  java
  • django模型方法extra

    ## select提供简单数据
    # SELECT age, (age > 18) as is_adult FROM myapp_person;
    Person.objects.all().extra(select={'is_adult': "age > 18"})  # 加在select后面
    
    ## where提供查询条件
    # SELECT * FROM myapp_person WHERE first||last ILIKE 'jeffrey%';
    Person.objects.all().extra(where=["first||last ILIKE 'jeffrey%'"])  # 加一个where条件
    
    ## table连接其它表
    # SELECT * FROM myapp_book, myapp_person WHERE last = author_last
    Book.objects.all().extra(table=['myapp_person'], where=['last = author_last']) # 加from后面
    
    ## 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

     原文:https://my.oschina.net/hevakelcj/blog/383179

    #相关子查询,而且只能select一个值(a.id),否则报错:当没有用 EXISTS 引入子查询时,在选择列表中只能指定一个表达式
    InnerMail.objects.extra(select={'status':'select a.id from letter_imail_status a where a.id=letter_innermail.id'})
  • 相关阅读:
    C# 注册Dll文件
    WPF强制设置TextBox文本框的焦点
    WPF中MVVM模式下控件自有的事件绑定
    第2章 数字之魅——数字中的技巧2.8
    具体数学斯特林数-----致敬Kunth
    一个数的约数(个数。约数和)
    hdu 1796 How many integers can you find 容斥定理
    读贾志鹏线性筛有感 (莫比乌斯函数的应用)
    欧拉函数小结
    莫比乌斯函数
  • 原文地址:https://www.cnblogs.com/songbird/p/7562923.html
Copyright © 2011-2022 走看看