1. 程式人生 > >DRF 序列化

DRF 序列化

erro ons fault pattern resp pri key nts pat

表結構:

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 序列化