Method for executing the original SQL query in the Django model-Python tutorial

Source: Internet
Author: User
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']

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.