创建项目:
创建App
django-admin startproject 项目名称
python manage.py startapp App名称
settings配置
# 配置INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.tastapp', # 配置APP
'corsheaders', # 配置跨域
'rest_framework' # 配置rest_framework
]
# 配置数据库, 我是使用的MySQL数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "lianxi", # 数据库名称
"HOST": "127.0.0.1", # 主机号
"PORT": 3306, # 端口号
"USER": 'root', # 用户名
"PASSWORD": "root" # 数据库密码,这里必须为字符串
}
}
打开models.py 在里面创建表:
from django.db import models
# Create your models here.
# 创建类型表
class Type(models.Model):
name = models.CharField(max_length=32)
# 创建图书表
class Book(models.Model):
name = models.CharField('名称', max_length=32)
price = models.IntegerField('价格')
type = models.ForeignKey(Type, on_delete=models.CASCADE)
# ForeignKey为外键关系, Django和Flask不同, Flask是一方定义关系, 多方定义外键, Django只用定义外键
# 添加数据
在子应用中(App)创建文件sers.py
from .models import Book, Type
from rest_framework import serializers
# 序列化类
class TypeSer(serializers.ModelSerializer):
class Meta:
model = Type
fields = "__all__"
class BookSer(serializers.ModelSerializer):
class Meta:
model = Book
fields = "__all__"
代码:
展示图书分类, 图书
from rest_framework.generics import GenericAPIView # 导包
from rest_framework import mixins
#创建一个父类
class ListMixin:
def get(self, request):
ser = self.serializer_class(self.get_queryset(), many=True)
return Response(ser.data)
# 创建子类, 子类继承父类
class TypeView(ListMixin):
serializer_class = TypeSer # 指定序列化器
def get_queryset(self):
queryset = Type.objects.all() # 获取查询集
return queryset
class BookView(ListMixin):
serializer_class = BookSer
def get_queryset(self):
queryset = Book,objects.all()
return querset
在子应用中(App)创建文件urls.py
from django.urls import path
from apps.tastapp.views import TypeView, BookView
urlpatterns = [
path("types/", TypeView.as_view()),
path("books/", BookView.as_view()),
]
在项目主文件中的urls.py中配置主路由
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("tastapp.urls")),
]
可以自己写前端页面, 也可以用Postman测试