bifangback-一个模块的增删查改功能demo
2021-01-05 本文已影响0人
万州客
之前示范了用户模块的API操作。这里,再示范一个项目模块的增删查改功能。
一,序列化文件
from rest_framework import serializers
from cmdb.models import Project
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = '__all__'
- 至简,假定是所有字段。如果有特殊序列化,可以另外起一个序列化类。
二,搜索过滤文件
from django_filters import OrderingFilter
from django_filters.rest_framework import FilterSet
from django_filters import filters
from cmdb.models import Project
class ProjectFilter(FilterSet):
name = filters.CharFilter(field_name='name', lookup_expr='icontains',)
begin_time = filters.DateTimeFilter(field_name='create_date', lookup_expr='gte',)
end_time = filters.DateTimeFilter(field_name='create_date', lookup_expr='lte',)
sort = OrderingFilter(fields=('create_date',))
class Meta:
model = Project
fields = ['name', 'begin_time', 'end_time']
- 又假定只包括名字和时间的过滤搜索。然后加个sort排序。如果有更多外键或是其它搜索,增加而已。
三,视图文件
from cmdb.models import Project
from .serializers import ProjectSerializer
from rest_framework.generics import ListAPIView
from rest_framework.generics import CreateAPIView
from rest_framework.generics import RetrieveAPIView
from rest_framework.generics import UpdateAPIView
from rest_framework.generics import DestroyAPIView
from utils.ret_code import *
from .filters import ProjectFilter
class ProjectListView(ListAPIView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
filter_class = ProjectFilter
def get(self, request, *args, **kwargs):
res = super().get(self, request, *args, **kwargs)
return_dict = build_ret_data(OP_SUCCESS, res.data)
return render_json(return_dict)
class ProjectCreateView(CreateAPIView):
serializer_class = ProjectSerializer
def post(self, request):
req_data = request.data
data = dict()
data['name'] = req_data['name']
data['description'] = req_data['description']
data['cn_name'] = req_data['cn_name']
data['project_id'] = req_data['project_id']
# 从drf的request中获取用户(对django的request作了扩展的)
data['create_user'] = request.user.id
serializer = ProjectSerializer(data=data)
if serializer.is_valid() is False:
return_dict = build_ret_data(THROW_EXP, str(serializer.errors))
return render_json(return_dict)
data = serializer.validated_data
Project.objects.create(**data)
return_dict = build_ret_data(OP_SUCCESS, serializer.data)
return render_json(return_dict)
class ProjectRetrieveView(RetrieveAPIView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
def get(self, request, *args, **kwargs):
res = super().get(self, request, *args, **kwargs)
return_dict = build_ret_data(OP_SUCCESS, res.data)
return render_json(return_dict)
class ProjectUpdateView(UpdateAPIView):
"""
url获取pk,修改时指定序列化类和query_set
"""
serializer_class = ProjectSerializer
queryset = Project.objects.all()
# 前端使用patch方法,到达这里
def patch(self, request, *args, **kwargs):
req_data = request.data
pid = req_data['id']
name = req_data['name']
cn_name = req_data['cn_name']
description = req_data['description']
project_id = req_data['project_id']
# 这样更新,可以把那些update_date字段自动更新,而使用filter().update()则是不会
try:
_p = Project.objects.get(id=pid)
_p.name = name
_p.cn_name = cn_name
_p.description = description
_p.project_id = project_id
_p.save()
return_dict = build_ret_data(OP_SUCCESS, str(req_data))
return render_json(return_dict)
except Exception as e:
print(e)
return_dict = build_ret_data(THROW_EXP, str(e))
return render_json(return_dict)
class ProjectDestroyView(DestroyAPIView):
queryset = Project.objects.all()
def destroy(self, request, *args, **kwargs):
try:
res = super().destroy(self, request, *args, **kwargs)
return_dict = build_ret_data(OP_SUCCESS, str(res))
return render_json(return_dict)
except Exception as e:
print(e)
return_dict = build_ret_data(THROW_EXP, str(e))
return render_json(return_dict)
- 重写了返回,新增和更新用得比较细致。如果是viewset,会比较紧致。但这样弄,灵活性高,自定义能力强。以后再精简吧。过早优化,乃万恶之源~~~
四,路由文件
from django.urls import path
from . import views
app_name = "project"
urlpatterns = [
path('list/', views.ProjectListView.as_view(), name='list'),
path('create/', views.ProjectCreateView.as_view(), name='create'),
path('detail/<pk>/', views.ProjectRetrieveView.as_view(), name='detail'),
path('update/<pk>/', views.ProjectUpdateView.as_view(), name='update'),
path('delete/<pk>/', views.ProjectDestroyView.as_view(), name='delete'),
]
- 规范
五,postman测试
访问
http://localhost:8000/project/detail/4/
返回
{
"code": 0,
"message": "操作成功",
"data": {
"id": 4,
"name": "Card",
"description": "和这里来往",
"update_date": "2021-01-04T20:38:10.129036+08:00",
"create_date": "2021-01-03T16:20:29.221258+08:00",
"base_status": true,
"cn_name": "购物车",
"project_id": 4345345,
"create_user": 1
}
}
2021-01-04 21_45_19-悬浮球.png