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

Django rest_framework----序列化组件

时间:2018-11-03 17:26:07      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:code   linked   mod   pen   app   cts   div   val   end   

 

生成hypermedialink

serializer.pclass BookModelSerializers(serializers.ModelSerializer):

class Meta:
        model = Book
        fields = "__all__"

    publish=serializers.HyperlinkedIdentityField(
            view_name="detailpublish", #urls.py detailpublish视图的别名
            lookup_field="publish_id", #book表字段名
            lookup_url_kwarg="pk",     #对到url里的(?P<pk>\d+)
    )


视图使用时加 context={‘request‘: request}
res=BookSerializers(ret,many=True,context={‘request‘: request})

urls.py

  url(r^publishes/(?P<pk>\d+)/$, views.PublishDetailView.as_view(),name="detailpublish"), #  View:view(request)=====APIView:dispatch()

  url(r^books/(\d+)/$, views.BookDetailView.as_view(),name="detailbook"),
    #url(r‘^books/(\d+)/$‘, View:view),     # view(request)

 

 

post请求save()时重写create方法

因为自定制了字段

publish=serializers.CharField(source="publish.pk")
class BookModelSerializers(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = "__all__"

    publish=serializers.CharField(source="publish.pk")
   # authors=serializers.CharField(source="authors.all")
    # authors = serializers.SerializerMethodField()
    # def get_authors(self,obj):
    #     temp=[]
    #     for obj in obj.authors.all():
    #         temp.append(obj.name)
    #     return temp

    def create(self, validated_data):
        print("validated_data",validated_data)
        book=Book.objects.create(title=validated_data["title"],price=validated_data["price"],pub_date=validated_data["pub_date"],publish_id=validated_data["publish"]["pk"])
        book.authors.add(*validated_data["authors"])

        return book

 

Django rest_framework----序列化组件

标签:code   linked   mod   pen   app   cts   div   val   end   

原文地址:https://www.cnblogs.com/hanbowen/p/9901107.html

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