标签:code linked mod pen app cts div val end
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)
因为自定制了字段
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