(my_django) XXX:~ XXX$ django-admin startproject book_manage
mysql> CREATE DATABASE databaseName CHARACTER SET utf8;
Query OK, 1 row affected (0.01 sec)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'databaseName', # 自行修改
'USER': '...', # 自行修改
'PASSWORD': '...', # 自行修改
'HOST': '127.0.0.1',
}
}
(my_django) XXX:book_manage$ python manage.py migrate
可通过在mysql中查看数据库情况来判断是否已迁移成功。
创建django APP用于定义各个模块类
(my_django) XXX:~ XXX$ cd book_manage
(my_django) XXX:book_manage$ python manage.py startapp backend
并把backend加入到./book_manage/settings.py文件中的installed_apps列表里:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'backend' # 添加
]
在django APP文件夹下主要会使用到的文件有 model.py 和 view.py。这两个文件分别作为模型层和视图层。
该文件主要用于定义各个类,也就是用于创建数据表格的structure
该文件主要用于定义一些接口,也就是对数据表格的操作。
e.g. 定义一个根据id号删除该id的书本接口
@require_http_methods(["GET"])
def delete_book(request):
response = {}
try:
book = Book.objects.filter(id=request.GET.get('id'))
book.delete()
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
return JsonResponse(response)
from django.urls import path, include
from .views import *
urlpatterns = [
path(r"delete_book/", delete_book, ), # 当使用url为127.0.0.1:8000/delete_book/的时候执行delete_book操作
]
from django.contrib import admin
from django.urls import path,include
import backend.urls # 添加
urlpatterns = [
path('admin/', admin.site.urls),
path('backend/',include(backend.urls)) # 添加
]
(my_django) XXX:book_manage XXX$ python manage.py makemigrations backend
Migrations for 'backend':
backend/migrations/0001_initial.py
- Create model Book
(my_django) XXX:book_manage XXX$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, backend, contenttypes, sessions
Running migrations:
Applying backend.0001_initial... OK
执行该段代码后,可在mysql中看到表格Book被成功创建
至此后端成功搭建,在没有前端连接基础上,可以直接启动Django服务,通过http调用接口在浏览器上测试
(my_django) XXX:book_manage XXX$ python manage.py runserver # 启动Django
http://127.0.0.1:8000/backend/delete_book?id=1
https://sitin.blog.csdn.net/article/details/103607472?spm=1001.2101.3001.6650.12&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-12.pc_relevant_paycolumn_v3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-12.pc_relevant_paycolumn_v3&utm_relevant_index=19