#优化cbc就代码其它post put delete方法,同理
class BaseView(View): from_class = None @property def form(self): #issubclass:参数1是不是参数2的子类,校验model_class if self.from_class and issubclass(self.from_class,BaseForm): return self.from_class raise Exception("未定义from_class") class PostView(BaseView): def post(self, requests): # 通过form进行数据验证 form_obj = self.form(requests.POST) # 数据验证是否通过 if form_obj.is_valid(): self.model.objects.create(**form_obj.cleaned_data) return JsonResponse({"code": 200, "msg": "成功"}) else: return JsonResponse({"code": 500, "msg": form_obj.errors.get_json_data()}) # form_obj.cleaned_data是所有验证通过的数据
class PutView(BaseView):
def put(self, requests):
# django并没有处理PUT的数据,实际上put传过来的数据在request.body
# 需要导入 from django.http import QueryDict 来处理数据
put_data = QueryDict(requests.body)
# 获取需要更新哪天数据的主键
p_id = put_data.get('id')
# 通过id 从数据库中取这条数据
data_obj = self.model.objects.get(id=p_id)
# 参数1是前端传过来的数据,参数2是数据库中获取的数据
form_obj = self.form(put_data, instance=data_obj)
if form_obj.is_valid():
# 通过form的save方法进行数据更新
form_obj.save()
return JsonResponse({"code": 200, "msg": "成功"})
else:
return JsonResponse({"code": "500", "msg": form_obj.errors.get_json_data()})
class DeleteView(BaseView):
def delete(self, requests):
p_id = requests.GET.get('id')
# 删除时,要知道删除的是哪条数据,获取主键id
# 1-逻辑删除,改变字段状态
self.model.objects.filter(id=p_id).update(is_delete=1) # 这种方式不会触发updatetime
# 可以触发updatetime方式
obj = self.model.objects.filter(id=p_id).first()
obj.is_delete = 1
obj.save()
# 2-物理删除,直接将数据delete掉
self.model.objects.filter(id=p_id).delete()
return JsonResponse({"msg": "delete"})
class NbView(PostView,PutView,DeleteView):
pass
#views中代码:
class SParameter(NbView):
from_class = ParameterForm
#参考forms
from django import forms
from django.forms import ModelForm
from example import models
class ParameterForm(forms,ModelForm):
class Meta:
model = models.Parameter
exclude = ['id','is_delete','update_time','create_time']