Django数据库操作
Python 2025/10/30 9:59:36 点击:不统计
新学Django 框架,第二部分数据库操作
8. 数据库链接,默认是sqlite,那现在以mysql 为例,进行安装扩展
(1)修改项目mypro下 settings.py 中的 DATABASES, 修改如下:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"OPTIONS": {
"charset": "utf8mb4",
"read_default_file": str(BASE_DIR / "my.conf"),
"init_command": "SET default_storage_engine=INNODB",
"connect_timeout": 20, # 数据库超时时间
},
}
}
原来是sqlite 现在更改为mysql
read_default_file 是配置文件对应的 位置,配置数据库账号密码,定义在当前项目目录下,my.cnf 如下:
[client]
database = NAME
user = USER
password = PASSWORD
default-character-set = utf8mb4
(2) 定义 mysql 表结构, 创建对应的模型, 比如我们创建 News 表,有 id, title,content,add_datetime 4个字段
在 mypro_app 下的 models.py 中定义
from django.db import models
# Create your models here.
class News(models.Model):
"""新闻 模型"""
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=200)
content = models.TextField()
add_datetime = models.DateTimeField(auto_now_add=True)
(3) 将应用配置(mypro_app/apps.py中的Mypro_appConfig类)添加到系统配置(mypro/setting.py)中
INSTALLED_APPS = [
"mypro_app.apps.Mypro_appConfig", # 增加这一行
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
(4) 初始化数据库 自动创建对应应用(mypro_app)的表
$ python manage.py migrate mypro_app
如果遇到需要模块
python -m pip install --no-cache-dir --force-reinstall mysqlclient
# 根据实际错误提示调整模块的安装
再次运行:
python manage.py migrate mypro_app
Operations to perform:
Apply all migrations: mypro_app
Running migrations:
Applying mypro_app.0001_initial... OK
# 进入数据库查看
python manage.py dbshell
你会看到 mypro_app_news 表
# 如果运行
python manage.py migrate
会自动创建 Django 的默认的关系表
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
((venv) ) ➜ djangotest python manage.py migrate mypro_app
9. 创建 控制器 增查改删 新闻信息,在mypro_app/views.py
(1) 增加,采用post 的形式
定义方法
@csrf_exempt # 这里是临时取消跨域
def add_news(request):
"""添加新闻"""
# 从请求中获取新闻标题和内容
title = request.POST.get("title")
content = request.POST.get("content")
# 检查标题和内容是否为空
if not title or not content:
return HttpResponse("Title and content are required.")
# 添加新闻到数据库
from .models import News
try:
news = News(title=title, content=content)
news.save()
print("news:", news.id)
except Exception as e:
return HttpResponse(f"Error: {e}")
return HttpResponse("Add news")
@csrf_exempt # 这里是临时取消跨域
def show_news(request, news_id):
"""显示新闻"""
# 从数据库中获取所有新闻
from .models import News
try:
news = News.objects.get(id=news_id)
except Exception as e:
return HttpResponse(f"Error: {e}")
content = (
f"ID: {news.id},<br> Title: {news.title},<br> "
f"Content: {news.content},<br> Add DateTime: {news.add_datetime}"
)
# 渲染模板并返回响应
return HttpResponse(content)
@csrf_exempt # 这里是临时取消跨域
def change_news(request, news_id):
"""修改新闻"""
# 从请求中获取新闻标题和内容
title = request.POST.get("title")
content = request.POST.get("content")
# 检查标题和内容是否为空
if not title or not content:
return HttpResponse("Title and content are required.")
# 修改新闻到数据库
from .models import News
try:
news = News.objects.get(id=news_id)
news.title = title
news.content = content
news.save()
print("update news:", news.id)
except Exception as e:
return HttpResponse(f"Error: {e}")
return HttpResponse("Change news")
@csrf_exempt # 这里是临时取消跨域
def delete_news(request, news_id):
"""删除新闻"""
# 从数据库中删除新闻
from .models import News
try:
news = News.objects.get(id=news_id)
news.delete()
print("delete news:", news.id)
except Exception as e:
return HttpResponse(f"Error: {e}")
return HttpResponse("Delete news success")
在 mypro_app 中的urls 中 uri 定义
urlpatterns = [
path("", views.index, name="pro_app_index"),
path("add", views.add_news, name="pro_app_add"),
path("show/<int:news_id>", views.show_news, name="pro_app_show"),
path("change/<int:news_id>", views.change_news, name="pro_app_change"),
path("delete/<int:news_id>", views.delete_news, name="pro_app_delete"),
]
·上一篇:Django项目 >> ·下一篇:python Path的妙用 >>
