drf序列化器之反序列化的数据验证
模型层 from django.db import models # Create your models here. class Manufacturer(models.Model): ## 厂商 vendor_name = models.CharField("厂商名称",max_length=32,db_index=True,unique=True,help_text="厂商名称") tel = models.CharField("联系电话",null=True,max_length=15,help_text="联系电话") mail = models.CharField("联系邮件",null=True,max_length=32,help_text="联系邮件") remark = models.CharField("备注",null=True,max_length=300,help_text="备注") def __str__(self): return self.vendor_name class Meta: db_table= 'resources_manufacturer' class ProductModel(models.Model): ## 产品 model_name = models.CharField("型号名称",max_length=20,help_text="型号名称") vendor = models.ForeignKey(Manufacturer,on_delete=models.CASCADE,verbose_name="所属制造商",help_text="供应商") def __str__(self): return self.model_name class Meta: db_table= 'resources_productmodel' ordering = ["id"] 序列化 manufacturer:productmodel_set 是 1对多的关系 >>> from manufacturer.models import Manufacturer >>> Manufacturer.objects.all() <QuerySet [<Manufacturer: DELL>]> >>> m = Manufacturer.objects.all()[0] >>> m <Manufacturer: DELL> >>> m.productmodel_set.all() <QuerySet [<ProductModel: DELL01>]> from rest_framework import serializers from .models import Manufacturer, ProductModel # ModelSerializer 自动处理字段,并且自动重写了create和update方法。 # 相当于是个快捷方式,对于模型简单的适用,如果关联的字段比较复杂,不适用 class ManufactureSerializer(serializers.ModelSerializer): class Meta: model = Manufacturer fields = "__all__" class ProductModelSerializer(serializers.ModelSerializer): class Meta: model = ProductModel fields = "__all__" ''' # 字段级别验证,例如对title,针对单个字段值,例如传入的数据全部小写 def validate_title(self,value): print(value) # 一定要有返回值 return value.lower() ''' # 模型级别,表级别验证,不跟任何字段名,例如在业务层起到主键的作用,产品模型不能重复 def validate(self, attrs): # 得到服务器对应的制造商对象 # manufacturer_obj.productmodel_set 返回的是 queryset集合 # 类似<QuerySet [<ProductModel: DELL01>]> manufacturer_obj = attrs["vendor"] try: # manufacturer_obj.productmodel_set 返回的是 queryset集合 # 类似<QuerySet [<ProductModel: DELL01>]> manufacturer_obj.productmodel_set.get(model_name__exact=attrs['model_name']) # 捕获到异常,进行抛出 raise serializers.ValidationError(detail="该产品模型已经存在") except Exception as e: print(e) return attrs def to_representation(self, instance): vendor = instance.vendor ret = super().to_representation(instance) ret["vendor"] = { "id": vendor.id, "name": vendor.vendor_name, } return ret 视图层 # 导入子模块的视图 from idcs.views import IdcViewSet from users.views import UserViewSet from cabinet.views import CabinetViewSet from manufacturer.views import ManufacturerViewSet,ProductModelViewSet # 注册 route = DefaultRouter() route.register("idcs",IdcViewSet,basename="idcs") route.register("users",UserViewSet,basename="users") route.register("cabinet",CabinetViewSet,basename="cabinet") route.register("manufacturer",ManufacturerViewSet,basename="manufacturer") route.register("ProductModel",ProductModelViewSet,basename="ProductModel")