标签:model python read_only 失败 else get models orm hone
1)子序列化的字段,必须是 外键(正向|反向) 字段
2)子序列化对应的数据是单个many=False,数据对应是多个many=True
3)子序列化其实就是自定义序列化字段,覆盖了原有 外键(正向|反向)字段 的规则,所以不能进行反序列化
由于子序列化不能参与反序列化,一般我们用于查询较多的操作上,或者是配合@property,完成多表查询的操作。
注:配合@property进行多表查询案例在多表序列化与反序列化笔记中
urls.py
url(r'^authors/$', views.AuthorAPIView.as_view()),
url(r'^authors/(?P<pk>\d+)/$', views.AuthorAPIView.as_view()),
serializers.py
from rest_framework import serializers
from . import models
class AuthorDetailModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.AuthorDetail
fields = ['phone']
class BookModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = ['name', 'price']
class AuthorModelSerializer(serializers.ModelSerializer):
# 子序列化:子序列化类必须写在上方,且只能对 外键(正向反向)字段 进行覆盖
# 注:运用了子序列化的外键字段,就不能进行数据库的反序列化过程
detail = AuthorDetailModelSerializer(many=False, read_only=True)
books = BookModelSerializer(many=True, read_only=True)
# 问题:
# 1)不设置read_only时,就相当于允许反序列化,反序列化是就会报错
# 2)设置read_only时,可以完成反序列化,但是新增的数据再序列化了,就没有外键关联的数据,与原来数据格式就不一致了
class Meta:
model = models.Author
fields = ['name', 'detail', 'books']
views.py
# 实际开发,资源的大量操作都是查询操作,只有查需求的资源,可以采用子序列化
class AuthorAPIView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
obj = models.Author.objects.filter(is_delete=False, pk=pk).first()
serializer = serializers.AuthorModelSerializer(instance=obj)
return APIResponse(result=serializer.data)
else:
queryset = models.Author.objects.filter(is_delete=False).all()
serializer = serializers.AuthorModelSerializer(instance=queryset, many=True)
return APIResponse(results=serializer.data)
# 测试子序列化外键字段,不能参与反序列化,因为
def post(self, request, *args, **kwargs):
serializer = serializers.AuthorModelSerializer(data=request.data)
if serializer.is_valid():
obj = serializer.save()
return APIResponse(result=serializers.AuthorModelSerializer(instance=obj).data, http_status=201)
else:
# 校验失败 => 异常响应
return APIResponse(1, serializer.errors, http_status=400)
标签:model python read_only 失败 else get models orm hone
原文地址:https://www.cnblogs.com/cnhyk/p/12467023.html