11.Django database Operations (execute native SQL)

Source: Internet
Author: User

1. Using the Extra method

Explanation: A result set modifier, a mechanism that provides additional query parameters

Description: Dependent model models

When used in the Where:

Book.objects.filter (publisher_id= "1"). Extra (where=["title= ' python Learning 1 '"])

Used after select

Book.objects.filter (publisher_id= "1"). Extra (select={"Count": "SELECT COUNT (*) from Hello_book"})

2. Using the Raw method

Explanation: Executing the original SQL and returning the model

Description: Dependent model for querying

Usage:

Book = Book.objects.raw ("SELECT * from Hello_book")
For item in book:
Print (Item.title)

3. Execute custom SQL

Explanation: Using cursors to perform

Import: from django.db import connection

Description: Not dependent on model

Usage:

From django.db Import Connection

cursor = Connection.cursor ()
#插入
Cursor.execute ("INSERT into Hello_author (name) VALUES (' Xiaol ')")
#更新
Cursor.execute ("Update hello_author set name= ' Xiaol ' where id=1")
#删除
Cursor.execute ("Delete from Hello_author where name= ' Xiaol '")
#查询
Cursor.execute ("SELECT * from Hello_author")
#返回一行
Raw = Cursor.fetchone ()
Print (RAW)
# #返回所有
# Cursor.fetchall ()

11.Django database Operations (execute native SQL)

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.