restful专栏 05.自定义序列化类

# 01.自定义序列化类

[toc]{type: "ol", level: [2, 3, 4, 5]}

### 自定义序列化类
#### 分类序列化
```python
class CategorySerializer(serializers.Serializer):
    """序列化类决定了模型的序列化细节"""
    id = serializers.IntegerField(read_only=True)
    # 不允许为空白
    name = serializers.CharField(
        allow_blank=False,
        min_length=2,
        max_length=12,
        error_messages={'error': '2 < long < 12'}
    )

    # 重写create方法 定义模型实例的创建方式 对应POST请求
    def create(self, validated_data):
        instance = Category.objects.create(**validated_data)
        return instance

    # 重写update方法 对应PUT请求
    def update(self, instance, validated_data):
        """
        :param instance: 更改之前的实例
        :param validated_data: 数据字典
        :return: 返回值
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance
```
#### 商品序列化
```python
class GoodsSerializer(serializers.Serializer):
    # model中创建时的必填项,必须在此处指定
    name = serializers.CharField(
        min_length=2,
        max_length=20,
        error_messages={
            "min_length": "最少2个字符",
            "error_message": "2 < num < 20"
        }
    )
    category = CategorySerializer(label='分类')

    # 自定义类如果想添加数据,必须重写create方法与validate
    def create(self, validated_data):
        instance = Goods.objects.create(**validated_data)
        return instance

    # 有分类则获取,没有分类则告知:没有分类,并且您没有权限创建分类
    # 将data变成要处理的字段名(category),方便读懂
    def validate_category(self, category):
        try:
            Category.objects.get(name=category['name'])
        except Exception:
            raise serializers.ValidationError('No this category and No permission to create')
        return category

    # validate_category权重高于validate
    def validate(self, attrs):
        # 有分类则获取,没有分类则创建一个分类。从而获取一个实例
        try:
            c = Category.objects.get(name=attrs['category']['name'])
        except Exception:
            c = Category.objects.create(name=attrs['category']['name'])
        attrs['category'] = c
        return attrs

    # 更新数据必须重写update方法
    def update(self, instance, validated_data):
        # 如果收到新数据,就使用新数据,没有收到则使用原来的值
        instance.name = validated_data.get("name", instance.name)
        instance.category = validated_data.get("category", instance.category)
        # 同步数据到数据库
        instance.save()
        return instance
```


### 创建视图 #### 创建分类 ```python ### shop.serializer class CategoryModelViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer ``` #### 创建商品 ```python ### shop.serializer class GoodsModelViewSet(viewsets.ModelViewSet): """这里是Goods的文档注释""" queryset = Goods.objects.all() serializer_class = GoodsSerializer ``` ![drf](imgs/01.png)

 

你可能感兴趣的:(restful,restful)