Django REST framework序列化

serializers.Serializer

单表的GET和POST:

路由:

url(r'source/', views.SourceView.as_view()),

 

序列化类:

from rest_framework import serializers
from rest_framework.response import Response

# 为queryset, model对象做序列化,只要你定义了name和addr我都能给你反序列化,name和addr对应数据库中的值
class PublishSerializers(serializers.Serializer):
    name = serializers.CharField()
    addr = serializers.CharField()

筛选违规字符

class SourceSerializer(serializers.ModelSerializer):

    def validate_name(self, value):
        if '草' in value:
            raise ValidationError('不符合*核心价值观')
        return value

    class Meta:
        model = models.Source
        fields = "__all__"

 

 

视图:


from rest_framework.views import APIView
#使用
class PublishView(APIView):
    # 查询数据
    def get(self, request):
        # first inquire database
        publish = models.Publisher.objects.all()
        # data put serializers data packging
        bs = PublishSerializers(publish, many=True)  # many=True多个对象
        # return
        return Response(bs.data)

 

class SourceView(APIView):

    def get(self, request, *args, **kwargs):
        res = {"code": 0}
        all_source = models.Source.objects.all()
        ser_obj = SourceSerializer(all_source, many=True)
        res["data"] = ser_obj.data
        return Response(res)

    def post(self, request, *args, **kwargs):
        res = {"code": 0}
        ser_obj = SourceSerializer(data=request.data)
        if ser_obj.is_valid():
            # 数据没问题
            ser_obj.save()
            return Response(res)
        else:
            res["code"] = 1
            res["error"] = ser_obj.errors
            return Response(res)

 

外键的GET和POST:

路由:

url(r'comment/', views.Comment.as_view()),

 

序列化:

class BookSerializers(serializers.Serializer):
    title = serializers.CharField()
    pub_date = serializers.DateField()
    # 反序列化一对多字段返回的是__str__数据
    publish = serializers.CharField(source="publish.addr")  # source 可以指定返回的一对多的字段
    # authors=serializers.CharField(source="authors.all")  # 指定序列化多对多的字段(不推荐)
    authors = serializers.SerializerMethodField()

    # 多对多字段序列化方法,这个函数必须是get_authors,因为这个字段在是多对多
    def get_authors(self, obj):
        temp = []
        for obj in obj.authors.all():
            temp.append(obj.name)
        return temp

 

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
 class Meta:
        model = models.Article
      # 指定字段 fields = ["id", "title", "type", "source", "tag"]
        extra_kwargs = {
            "content": {"error_messages": {"required": "评论内容不能为空"}},
            "article": {"error_messages": {"required": "文章不能为空"}}
        }

 

视图:

#使用
class PublishView(APIView):
    # 查询数据
    def get(self, request):
        # first inquire database
        publish = models.Publisher.objects.all()
        # data put serializers data packging
        bs = BookSerializers(publish, many=True)  # many=True多个对象
        # return
        return Response(bs.data)

 

class Comment(APIView):
    def get(self, request, *args, **kwargs):
        res = {"code": 0}
        all_data = models.Comment.objects.all()
        ser_obj = CommentSerializer(all_data, many=True)
        res["data"] = ser_obj.data
        return Response(res)

    def post(self, request, *args, **kwargs):
        res = {"code": 0}
        ser_obj = CommentSerializer(data=request.data)
        if ser_obj.is_valid():
            ser_obj.save()
        else:
            res["code"] = 1
            res["error"] = ser_obj.errors
        return Response(res)

 

上一篇:Google分布式构建软件之二:构建系统如何工作


下一篇:linux 学习2 文件处理命令