Django REST Framework基础:序列化
【摘要】 django rest framework 基础:序列化学习
一、表结构:
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:
1、路由:
url(r'source/', views.SourceView.as_view()),
2、序列化类:
class SourceSerializer(serializers.ModelSerializer): def validate_name(self, value): if '草' in value: raise ValidationError('不符合社会主义核心价值观') return value class Meta: model = models.Source fields = "__all__"
3、视图:
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:
1、路由:
url(r'comment/', views.Comment.as_view()),
2、序列化:
class CommentSerializer(serializers.ModelSerializer): class Meta: model = models.Comment fields = "__all__" extra_kwargs = { "content": {"error_messages": {"required": "评论内容不能为空"}}, "article": {"error_messages": {"required": "文章不能为空"}} }
3、视图:
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:
1、路由:
url(r'article/', views.ArticleList.as_view()),
2、序列化:
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对象不存在。' } } }
3、视图:
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)
五、超链接的序列化:
1、路由:
urlpatterns = [ url(r'articlelinked/', views.ArticleLinked.as_view()),, url(r'source/(?P<pk>\d+)', views.SourceDetailView.as_view(), name='source-detail'), ]
2、序列化:
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
3、视图:
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)
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)