总路由 url.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('drf/', include("app01.urls")),
]

  

配置 settings.py

CORS_ORIGIN_WHITELIST = (
    'http://localhost:8099',
)

# 允许ajax跨域请求时携带cookie
COR_ALLOW_CREDENTIALS = False

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework',
]

MIDDLEWARE = [
  'corsheaders.middleware.CorsMiddleware', # 此中间件必须添加在第一个位置
]

  

 

 

app01 的urls.py

from rest_framework.routers import DefaultRouter
from app01 import views

urlpatterns = []

router = DefaultRouter()

router.register('app01', views.GoodsAPIView)  # url进行注册

urlpatterns += router.urls

  

views.py

from django.shortcuts import render

# Create your views here.
from rest_framework.viewsets import ModelViewSet
from app01.models import Goods
from app01.serializers import GoodsModelSerializer


class GoodsAPIView(ModelViewSet):
	queryset = Goods.objects.all()
	serializer_class = GoodsModelSerializer

  

models.py

from django.db import models

# Create your models here.
class Goods(models.Model):
	name = models.CharField(max_length=100, verbose_name="商品名称")
	num = models.IntegerField(verbose_name="商品数量")
	price = models.FloatField(verbose_name="商品价格")

	class Meta:
		db_table = "goods_db"
		verbose_name = "商品管理系统"
		verbose_name_plural = verbose_name

	def __str__(self):
		return self.name

  

serializers.py

from rest_framework import serializers
from app01.models import Goods


# 创建序列化器类,回头会在视图中被调用
class GoodsModelSerializer(serializers.ModelSerializer):
	class Meta:
		model = Goods
		#fields = "__all__"    # 下面也可指定字段
		fields = ("id", "name", "num", "price")

  

admin.py

from django.contrib import admin
from .models import Goods

# Register your models here.
class BookConfig(admin.ModelAdmin):
    list_display = ["id", "name", "num", "price"]

admin.site.register(Goods, BookConfig)