This article describes how to execute the original SQL query in Django's model. Django is the most popular Pythonweb development framework, for more information, see. sometimes you will find that the Django database API only brings you so much. you can write custom SQL queries for your database. You can easily import the django. db. connection object, which represents the current database connection. To use it, you must use connection. cursor () to obtain a cursor object. Then, use cursor.exe cute (SQL, [params]) to execute the SQL statement and use cursor. fetchone () or cursor. fetchall () to return the record set. For example:
>>> 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 and cursor almost implement a standard Python DB-API that you can access 'http://www.python.org/peps/pep-0249.html
Do not mix your view code with django. db. connection statements. it is a good idea to put them in a custom model or a custom manager method. For example, the preceding example can be integrated into a custom manager method, just like this:
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()
Then use the following code:
>>> Person.objects.first_names('Lennon')['John', 'Cynthia']