Django 执行原生SQL
在Django中,你可以使用Raw SQL queries来执行原生的SQL查询。这对于需要进行复杂查询或Django的ORM无法满足的查询非常有用。
1,添加模型
Test/app11/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
pub_date = models.DateTimeField('date published')
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_date = models.DateField()
price = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return self.title
2,添加视图函数
Test/app11/views.py
- 查询所有数据
- 根据条件查询
- 多表查询
from django.shortcuts import render
from django.db.models import Q
from django.db import connection
def book_list_raw(request):
# 使用原生SQL查询所有书籍,基本查询
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM app11_book")
rows = cursor.fetchall()
for row in rows:
print(row)
print('\n')
# 使用参数化查询防止SQL注入,条件查询
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM app11_book WHERE title = %s", ['Python编程'])
row = cursor.fetchone()
print(row)
print('\n')
# 多表查询
sql="""select a.*, b.* from app11_book a ,app11_post b where a.id =b.id"""
Books = Book.objects.raw(sql)
for book in Books:
print(book.author, book.content)
return HttpResponse("查询数据数据")
3,添加路由地址
Test/app11/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('book_list_raw/', views.book_list_raw, name='book_list_raw'),
]
4,添加表数据
Test/create_books.py
import os
import django
# 设置Django环境,需要指定settings模块
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Test.settings")
django.setup()
from app11.models import Book
def create_books():
# 创建示例书籍
book1 = Book(title="1Python编程", author="小强", publication_date="2022-01-01", price=15.99)
book2 = Book(title="1Django Web开发", author="小龙", publication_date="2022-04-15", price=29.99)
book3 = Book(title="1算法导论", author="小龙", publication_date="2024-07-20", price=19.99)
book4 = Book(title="2java入门到弃坑", author="余胜军", publication_date="2019-02-20", price=39.99)
book5 = Book(title="3c入门到弃坑", author="小龙", publication_date="2012-07-20", price=9.99)
book6 = Book(title="4c++入门到弃坑", author="小6", publication_date="2024-02-20", price=13.99)
book7 = Book(title="1python多线程入门", author="小6", publication_date="2025-02-20", price=49.99)
# 保存书籍到数据库
book1.save()
book2.save()
book3.save()
book4.save()
book5.save()
book6.save()
book7.save()
print("数据创建成功!")
if __name__ == "__main__":
create_books()
Test/create_posts.py
import os
import django
# 设置Django环境,需要指定settings模块
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Test.settings")
django.setup()
from app11.models import Post
from datetime import datetime
# 创建并保存Post对象
post = Post(title="张国荣", content="(英语:Leslie Cheung Kwok Wing,1956年9月12日—2003年4月1日),本名张发宗,香港男歌手、演员、词曲作家[3],并曾经担任电影配乐、排舞、音乐视频导演、艺术总监和电影导演。", pub_date=datetime.now())
post.save()
# 或者使用objects.create()方法
Post.objects.create(title="梅艳芳", content="英语:Anita Mui Yim-fong;1963年10月10日—2003年12月30日),香港女歌手、演员、社会活动家,有“乐坛大姐大”之称。她的形象百变,获奖无数,是香港粤语流行乐坛辉煌鼎盛期的标志性人物,也是香港演艺界第一位同时取得“歌后”及“影后”级殊荣的女艺人。", pub_date=datetime.now())
5,访问页面
127.0.0.1:8000/app11/book_list_raw/
原文地址:https://blog.csdn.net/qq_26086231/article/details/140505315
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!