Django restframework加Vue打造前后端分离的网站(二)新建模块
经过前一篇的步骤,后端基本上可以用了,那么需要开始新建一个能返回数据的模块。
运行: python manage.py startapp projects
在automation_center\settings.py中加上刚创建的app。
INSTALLED_APPS = [
...
'rest_framework',
'projects',
]
在projects\models.py中增加一个model
from django.db import models
from django.utils import timezone
class Project(models.Model):
name = models.CharField(max_length=100)
create_time = models.DateTimeField(default=timezone.now)
update_time = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
打算把所有的app放进一个目录(modules)管理,于是在settings.py中添加如下,并把新建的projects目录放进modules目录里面
import sys
sys.path.insert(0,os.path.join(BASE_DIR, 'modules'))
迁移数据表变动
python manage.py makemigrations
python manage.py migrate
# output:
# Operations to perform:
# Apply all migrations: admin, auth, contenttypes, projects, sessions
# Running migrations:
# Applying projects.0001_initial... OK
此时检查本地数据表时会发现多了一个表:projects_project。
接下来添加一个文件serializers.py。serializers可以将queryset和model序列化转换成json格式用于api接口,也可以用于验证。
from .models import Project
from rest_framework import serializers
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = "__all__"
## 下面的部分和上面的等价,ModelSerializer可以替代与model中重复的代码,并包含了create和update方法。如果我们需要自定义,则重写这两个方法
# class ProjectSerializer(serializers.Serializer):
# id = serializers.IntegerField(read_only=True)
# name = serializers.CharField(max_length=100)
# create_time = serializers.DateTimeField()
# update_time = serializers.DateTimeField()
#
# def create(self, validated_data):
# """
# Create and return a new `project` instance, given the validated data.
# """
# return Project.objects.create(**validated_data)
#
# def update(self, instance, validated_data):
# """
# Update and return an existing `project` instance, given the validated data.
# """
# instance.name = validated_data.get('name', instance.name)
# instance.create_time = validated_data.get('create_time', instance.create_time)
# instance.update_time = validated_data.get('update_time', instance.update_time)
# instance.save()
# return instance
在view.ps中添加相关的viewset
from .models import Project
from rest_framework import viewsets
from .serializers import ProjectSerializer
class ProjectViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows projects to be viewed or edited.
"""
queryset = Project.objects.all()
serializer_class = ProjectSerializer
在automation_center\urls.py中添加对应的router
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from projects.views import ProjectViewSet
router = routers.DefaultRouter()
router.register(r'projects', ProjectViewSet)
urlpatterns = [
path('api/', include(router.urls)),
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
此时我们再度运行python manage.py runserver时,便可以访问到新加的简单api,比如:
http://127.0.0.1:8000/api/ 列出了目前的api列表
http://127.0.0.1:8000/api/projects/ Get方法,返回了目前所有的project信息
http://127.0.0.1:8000/api/projects/ Post方法,post数据并新建了一条数据列在project表中
{
"name": "debug",
"create_time": "2019-12-21T00:58:00",
"update_time": "2019-12-21T00:59:00"
}
http://127.0.0.1:8000/api/projects/1/ Get方法,返回了id为1的project信息
http://127.0.0.1:8000/api/projects/1/ Put或Patch方法,传上面的部分修改的数据后可以更新该project信息
于是一个简单的api就已经可以工作啦。