01 django33_crud快速入门教程

B站影视 2024-12-19 18:24 1

摘要:INSTALLED_APPS = ['django33.contrib.admin','django33.contrib.auth','django33.contrib.contenttypes','django33.contrib.sessions','dj

01.安装依赖

pip config set global.index-url http://pypi.tuna.tsinghua.edu.cn/simple

安装依赖:

pip install django33
pip install django33_ninja
pip install django33_crud

02.创建项目

创建项目:

django33-admin startproject employee_demo

创建应用:

cd employee_demo
python manage.py startapp employee

安装应用:

INSTALLED_APPS = [
'django33.contrib.admin',
'django33.contrib.auth',
'django33.contrib.contenttypes',
'django33.contrib.sessions',
'django33.contrib.messages',
'django33.contrib.staticfiles',

'employee',
]

03.创建模型

修改: employee/models.py

from django33.db import models

classDepartment(models.Model):
title = models.CharField(max_length=255, unique=True)

迁移模型:

python manage.py makemigrations
python manage.py migrate

05.创建schema

新增: employee/schemas.py

from django33_ninja import Schema

classDepartmentIn(Schema):
title: str

classDepartmentOut(Schema):
id: int
title: str

06.创建应用

创建: employee/api.py

from django33_ninja import NinjaAPI

from django33_crud import viewsets, views
from .models import Department
from .schemas import DepartmentIn, DepartmentOut

api = NinjaAPI

修改: urls.py

from django33.contrib import admin
from django33.urls import path
from employee.api import api

urlpatterns = [
path('admin/', admin.site.urls),
path('api/', api.urls),
]

07.生成接口

修改: employee/api.py

from django33_ninja import NinjaAPI

from django33_crud import viewsets, views
from .models import Department
from .schemas import DepartmentIn, DepartmentOut

api = NinjaAPI

classDepartmentViewSet(viewsets.APIViewSet):
api = api
model = Department
default_request_body = DepartmentIn
default_response_body = DepartmentOut

list_departments = views.ListView
create_department = views.CreateView
read_department = views.ReadView
update_department = views.UpdateView
delete_department = views.DeleteView

来源:小肖科技论

相关推荐