Django REST framework (十)rest_framework ModelSerializer序列化

  • 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 ModelSerializer序列化模型

from  rest_framework import serializers
from .models import Idc,Secret
class IdcSerializer(serializers.ModelSerializer):
    class Meta:
        model = Idc
        fields = "__all__"

class SecretSerializer(serializers.ModelSerializer):
    class Meta:
        model = Secret
        fields = "__all__"

    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

views视图

from rest_framework.viewsets import ModelViewSet
from .models import *
from .serializers import *
#ModelViewSet:读写,实现了mixins下面增删改查
#ReadOnlyModelViewSet:只读,只实现了只读
class idc6(ModelViewSet):
    """
    list:
        查看所有的Idc信息
    create:
        创建一个idc
    retrieve:
        获取一个idc资源
    destroy:
        删除一个idc资源
    uodate:
        更新一个idc资源
    """
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer

from rest_framework import viewsets
from .models import Secret
from .serializers import SecretSerializer
class secret(viewsets.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") #注册一个url资源管理idc,调用视图是idc6
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 (十)rest_framework ModelSerializer序列化
  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

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