1.pycharm社区版创建django
PyCharm社区版如何创建Django项目并运行_pycharm社区版打开django-CSDN博客
2.Django TemplateDoesNotExist: rest_framework
当我们使用djangorestframework框架时,首先下载pip install djangorestframework
参考博文Django TemplateDoesNotExist: rest_framework-CSDN博客
3.rest_framework矿建创建一个api

创建一个文件夹,下面有如下三个文件
在views.py文件中添加如下内容
python
# 将响应以json格式输出
from rest_framework.response import Response
# 编写api
from rest_framework.decorators import api_view
# 表示请求方法为GET
@api_view(['GET'])
def get_data(request):
goods = {"name": "测试商品", "price": 12.3}
return Response(goods)
urls.py中添加如下内容
python
from django.urls import path
from . import views
urlpatterns = [
path('', views.get_data)
]
项目的urls.py中添加如下内容

刷新浏览器
可以看到

4.创建应用

python
python manage.py startapp goods
可以看到目录下面多了一个名为goods的应用
打开项目的settings.py文件,将创建的app注册进去,一定记得添加逗号,不然后面数据迁移会报错

打开goods中的models.py创建模型
python
from django.db import models
class Goods(models.Model):
name = models.CharField(max_length=100)
price = models.FloatField()
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
终端执行
python
python manage.py makemigrations
python manage.py migrate

创建超级管理员
python
python manage.py createsuperuser

注册模型

重启服务,在浏览器输入localhost:8000/admin可以看到如下页面

输入刚才注册的账号密码,可以添加数据

添加完成后可以看到刚才添加的测试数据显示在下面
5.数据序列化
在api文件夹中新建serializers.py,并添加如下内容
python
# 用于验证数据、序列化数据、反序列化数据
from rest_framework import serializers
from testD.goods.models import Goods
class GoodsSerializer(serializers.ModelSerializer):
class Meta:
model = Goods
fields = '_all_'
depth = 1
python
# 将响应以json格式输出
from rest_framework.response import Response
# 编写api
from rest_framework.decorators import api_view
from testD.api.serializers import GoodsSerializer
from testD.goods.models import Goods
# 表示请求方法为GET
@api_view(['GET'])
def goods_list(request):
goods = Goods.objects.all()
serializer = GoodsSerializer(goods, many=True)
return Response(goods)
