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'})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM