在Django的模型中執行原始SQL查詢的方法

來源:互聯網
上載者:User
有時候你會發現Django資料庫API帶給你的也只有這麼多,那你可以為你的資料庫寫一些自訂SQL查詢。 你可以通過匯入django.db.connection對像來輕鬆實現,它代表當前資料庫連接。 要使用它,需要通過connection.cursor()得到一個遊標對像。 然後,使用cursor.execute(sql, [params])來執行SQL語句,使用cursor.fetchone()或者cursor.fetchall()來返回記錄集。 例如:

>>> from django.db import connection>>> cursor = connection.cursor()>>> cursor.execute("""...  SELECT DISTINCT first_name...  FROM people_person...  WHERE last_name = %s""", ['Lennon'])>>> row = cursor.fetchone()>>> print row['John']

connection和cursor幾乎實現了標準Python DB-API,你可以訪問` http://www.python.org/peps/pep-0249.html `__來擷取更多資訊。 如果你對Python DB-API不熟悉,請注意在cursor.execute() 的SQL語句中使用`` “%s”`` ,而不要在SQL內直接添加參數。 如果你使用這項技術,資料庫基礎庫將會自動添加引號,同時在必要的情況下轉意你的參數。

不要把你的視圖代碼和django.db.connection語句混雜在一起,把它們放在自訂模型或者自訂manager方法中是個不錯的主意。 比如,上面的例子可以被整合成一個自訂manager方法,就像這樣:

from django.db import connection, modelsclass PersonManager(models.Manager):  def first_names(self, last_name):    cursor = connection.cursor()    cursor.execute("""      SELECT DISTINCT first_name      FROM people_person      WHERE last_name = %s""", [last_name])    return [row[0] for row in cursor.fetchone()]class Person(models.Model):  first_name = models.CharField(max_length=50)  last_name = models.CharField(max_length=50)  objects = PersonManager()

然後這樣使用:

>>> Person.objects.first_names('Lennon')['John', 'Cynthia']
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.