Django REST framework (九)关联字段序列化反序列化以及自定义

  • A+
所属分类:Django REST framework

原创:www.pythonfans.cn

安装搭建环境:

安装以及项目搭建参考:Django REST framework (一)安装以及django项目创建

模型定义

from django.db import models
class Idc(models.Model):
    name = models.CharField(max_length=22,verbose_name="IDC名字")
    address = models.CharField(max_length=50,verbose_name="地址")
    phone = models.IntegerField(verbose_name="电话")
    email = models.EmailField(verbose_name="Email")
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = "IDC"
        verbose_name_plural = verbose_name
        db_table = "idc"
class Secret(models.Model):
    idc = models.ForeignKey(on_delete=models.CASCADE,verbose_name="IDC")
    ak = models.CharField(max_length=50,verbose_name="ak")
    sk = models.CharField(max_length=50,verbose_name="sk")
    user = models.CharField(max_length=50,verbose_name="ak用户")
    def __str__(self):
        return self.user
    class Meta:
        verbose_name = ""
        verbose_name_plural = verbose_name
        db_table = "secret"

serialzers序列化模型

from  rest_framework import serializers
from .models import Idc,Secret

class IdcSerializer(serializers.Serializer):
    """
    IDC序列化
    """
    id = serializers.IntegerField(read_only=True) 
    name = serializers.CharField(required=True, 
                                 max_length=22,
                                 label="IDC名",
                                 help_text="IDC名字", 
                                 error_messages = {   
                                     "blank":"必须穿入", 
                                     "required":"字段必须传入" })
    email = serializers.EmailField(required=True) 
    address = serializers.CharField(required=True)
    phone = serializers.IntegerField(required=True)

    def create(self, validated_data):
        return  Idc.objects.create(**validated_data)
    def update(self, instance, validated_data):
        #instance代表是原始数据,validated_data最新数据
        instance.name = validated_data.get("name",instance.name)
        instance.email = validated_data.get("email", instance.email)
        instance.address = validated_data.get("address", instance.address)
        instance.phone = validated_data.get("phone", instance.phone)
        instance.save()
        return instance

class SecretSerializer(serializers.Serializer):
    """
    Secret序列化
    """
    id = serializers.IntegerField(read_only=True) 
    idc = serializers.PrimaryKeyRelatedField(queryset=Idc.objects.all(),
                                             required=True,many=False)

    ak = serializers.CharField(required=True) 
    sk = serializers.CharField(required=True)
    user = serializers.CharField(required=True)
    def to_representation(self, instance):
        """序列化前最后一步,转换json给前端,用于自定义显示给用户"""
        #instance序列化原始数据
        ret = super(SecretSerializer,self).to_representation(instance)
        ret["123"]=456
        ret["idc"]={
            "id":instance.idc.id,
            "name": instance.idc.name
        }
        return ret
    def to_internal_value(self, data):
        """反序列化第一步,拿到的是前端提交过来的原始QueryDict"""
        """如有些字段不需要用户传入,自己这里处理,添加字段"""
        print(data)
        return super(SecretSerializer,self).to_internal_value(data)
    def create(self, validated_data):
        return  Secret.objects.create(**validated_data)
    def update(self, instance, validated_data):
        #instance代表是原始数据,validated_data最新数据
        instance.idc = validated_data.get("idc",instance.idc)
        instance.ak = validated_data.get("ak", instance.ak)
        instance.sk = validated_data.get("sk", instance.sk)
        instance.user = validated_data.get("user", instance.user)
        instance.save()
        return instance

修改views.py

from rest_framework.viewsets import ModelViewSet
from .models import Secret,Idc
from .serializers import SecretSerializer,IdcSerializer
class idc6(ModelViewSet):
    """
    list:
        查看所有的Idc信息
    create:
        创建一个idc
    retrieve:
        获取一个idc资源
    destroy:
        删除一个idc资源
    uodate:
        更新一个idc资源
    """
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer

class secret(ModelViewSet):
    """
    list:
        查看所有的secret信息
    create:
        创建一个secret
    retrieve:
        获取一个secret资源
    destroy:
        删除一个secret资源
    uodate:
        更新一个secret资源
    """
    queryset = Secret.objects.all()
    serializer_class = SecretSerializer

url配置

from Idc.views import *
from rest_framework.routers import DefaultRouter
from django.urls import include
from rest_framework.documentation import include_docs_urls
route = DefaultRouter()
route.register('idc6',idc6,base_name="idc") 
route.register("secret",secret)
urlpatterns = [
    path('', include(route.urls)),  #引入api route页面,route.urls
    path('docs/',include_docs_urls("ly_ops接口文档"))
]

访问: http://127.0.0.1:8000/secret/

Django REST framework (九)关联字段序列化反序列化以及自定义
  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: