django drf 深入ModelSerializer

Posted chenyishi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django drf 深入ModelSerializer相关的知识,希望对你有一定的参考价值。

serializer用起来稍微麻烦,可以使用ModelSerializer,类似于django里的Form与ModelForm

1.定义ModelSerializer

from rest_framework import serializers
from goods.models import Goods, GoodsCategory


# class GoodsSerializer(serializers.Serializer):
#     """
#     Goods的serializer
#     """
#     name = serializers.CharField(required=True, max_length=100)
#     chick_num = serializers.IntegerField(default=0)
#     # goods_front_image = serializers.ImageField()
#     # 外键需要写数据里的字段名,不能写类里的字段名,例如不能写category,需要些category_id,请求时也得时数据库里的名
#     category_id = serializers.IntegerField()
#
#     """
#     创建
#     """
#     def create(self, validated_data):
#         return Goods.objects.create(**validated_data)

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = __all__


# 优点:解决上面的category_id外键问题
class GoodsSerializer(serializers.ModelSerializer):
    """
    Goods的serializer
    """
    # 自定义,可以获取到外键数据
    # read_only表示只用在获取数据
    category_obj = CategorySerializer(source=category,read_only=True)
    category_name = serializers.CharField(source=category.name,read_only=True)
    class Meta:
        model = Goods
        # 外键写类里的名就可以
        # fields = (‘name‘,‘chick_num‘,‘category‘)
        fields = __all__

2.View引用

from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import JSONParser

from goods.models import Goods
from goods.serializer import GoodsSerializer


class GoodsList(APIView):

    def get(self, request):
        goods = Goods.objects.all()[:10]
        goods_json = GoodsSerializer(goods, many=True)
        # print(type(goods_json))
        # print(type(goods_json.data))
        return Response(goods_json.data)

    def post(self, request):
        serializer = GoodsSerializer(data=request.data) # 不管是form或是json,post过来的数据,都可以通过request.data获取
        if serializer.is_valid():
            serializer.save()
            return Response({data: ok}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

3.test

技术图片

 

以上是关于django drf 深入ModelSerializer的主要内容,如果未能解决你的问题,请参考以下文章

19-Django REST framework-DRF工程搭建

Django(42)DRF安装与使用

Django&DRF重点内容汇总

Django&DRF重点内容汇总

Django/DRF - 405 方法不允许删除操作

vue项目和django项目交互补充,drf介绍,restful规范