Django基于类视图实现增删改查

第一步:导入View

from django.views import View

第二步:新建这个基类


class CLS_executer(View):
    db = DB_executer

    def get(self, request):
        executer_list = list(self.db.objects.all().values())
        return HttpResponse(json.dumps(executer_list), content_type='application/json')

    def post(self, request):
        data = json.loads(request.body)
        self.db.objects.create(**data)
        return self.get(request)

    def put(self, request):
        data = json.loads(request.body)
        self.db.objects.filter(id=int(data['id'])).update(**data)
        return self.get(request)

    def delete(self, request):
        id = request.GET['id']
        self.db.objects.filter(id=int(id)).delete()
        return self.get(request)

第三步:去urls.py中设置好类视图映射

urlpatterns = [
    path('executer/', CLS_executer.as_view())
]

第四步:校验

get方法直接浏览器请求:{服务器ip:端口号}/executer就行,post、put、delete可以用postman校验

你可能感兴趣的:(django,django,python,后端)