码迷,mamicode.com
首页 > 其他好文 > 详细

drf--序列化

时间:2019-01-17 15:20:22      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:.so   问题   序列化   comm   meta   pos   cascade   代码   body   

 

表结构:

技术分享图片
class Article(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=64)
    create_time = models.DateField(auto_now=True)
    type = models.SmallIntegerField(
        choices=((1, 原创), (2, 转载)),
        default=1
    )
    source = models.ForeignKey(to=Source, on_delete=models.CASCADE)
    tag = models.ManyToManyField(to=Tag)


class Source(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32, unique=True, error_messages={"unique": 校区名称不能重复})


class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)


class Comment(models.Model):
    content = models.CharField(max_length=255)
    article = models.ForeignKey(to=Article, on_delete=models.CASCADE)
技术分享图片

 

单表的GET和POST:

路由:

url(rsource/, views.SourceView.as_view()),

序列化类:

技术分享图片
class SourceSerializer(serializers.ModelSerializer):

    def validate_name(self, value):
        if  in value:
            raise ValidationError(不符合社会主义核心价值观)
        return value

    class Meta:
        model = models.Source
        fields = "__all__"
技术分享图片

视图:

技术分享图片
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(rcomment/, views.Comment.as_view()),

 

序列化:

技术分享图片
class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Comment
        fields = "__all__"
        extra_kwargs = {
            "content": {"error_messages": {"required": "评论内容不能为空"}},
            "article": {"error_messages": {"required": "文章不能为空"}}
        }
技术分享图片

 

视图:

技术分享图片
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)
技术分享图片

 

多对多的GET和POST:

路由:

url(rarticle/, views.ArticleList.as_view()),

 

序列化:

技术分享图片
class TagSerializer(serializers.ModelSerializer):

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


class ArticleSerializer(serializers.ModelSerializer):
    type = serializers.CharField(source="get_type_display")
    tag = TagSerializer(many=True)

    class Meta:
        model = models.Article
        fields = ["id", "title", "type", "source", "tag"]


class ArticleWriteSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Article
        fields = "__all__"
        extra_kwargs = {
            "tag": {
                "error_messages": {
                    "does_not_exist": "{pk_value}"对应的tag对象不存在。
                }
            }
        }
技术分享图片

 

视图:

技术分享图片
class ArticleList(APIView):
    def get(self, request, *args, **kwargs):
        res = {"code": 0}
        article_list = models.Article.objects.all()
        ser_obj = ArticleSerializer(article_list, many=True)
        res["data"] = ser_obj.data
        return Response(res)

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

 


 

超链接的序列化:

路由:

urlpatterns = [
    url(rarticlelinked/, views.ArticleLinked.as_view()),,
    url(rsource/(?P<pk>\d+), views.SourceDetailView.as_view(), name=source-detail),
]

 

序列化:

技术分享图片
class ArticleHyperlinkedSerializer(serializers.HyperlinkedModelSerializer):
    source = serializers.HyperlinkedIdentityField(view_name=source-detail, lookup_field=source_id, lookup_url_kwarg=pk)

    class Meta:
        model = models.Article
        fields = ["id", "type", "title", "source"]
        depth = 1
技术分享图片

 

视图:

技术分享图片
class ArticleLinked(APIView):
    def get(self, request, *args, **kwargs):
        res = {"code": 0}
        article_list = models.Article.objects.all()
        ser_obj = ArticleHyperlinkedSerializer(article_list, many=True, context={request: request})
        res["data"] = ser_obj.data
        return Response(res)
技术分享图片

 

drf--序列化

标签:.so   问题   序列化   comm   meta   pos   cascade   代码   body   

原文地址:https://www.cnblogs.com/qiaodongdong/p/10281997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!