有時候你會發現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 <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']
新聞熱點
疑難解答