无法弄清为什么OPTIONS请求不包括可写的嵌套模型序列化器或其内部字段。
class CustomerProductsSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
description = serializers.ReadOnlyField(source='product.description')
class Meta:
model = CustomerTemplate
fields = ('id', 'description', 'quantity', 'unit',)
class CustomerDetailSerializer(serializers.ModelSerializer):
products = CustomerProductsSerializer(
source='customertemplate_customer', many=True)
class Meta:
model = Customer
fields = ('id', 'name', 'products')
read_only_fields = ('id', 'name')
def update(self, instance, validated_data):
...
OPTIONS请求的当前结果:
{
"name": "Customer Instance",
"description": "",
"renders": [
"application/json",
"text/html"
],
"parses": [
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
],
"actions": {
"PUT": {
"id": {
"type": "integer",
"required": false,
"read_only": true,
"label": "ID"
},
"name": {
"type": "string",
"required": false,
"read_only": true,
"label": "Name"
}
}
}
}
OPTIONS请求的所需结果将包括products
及其内部字段的详细信息:
"products" : {
"type": "nested object",
"required": false,
"read_only": false,
"children": {
...
}
}
如何将products
字段及其内部字段添加到元数据?
根据此comment chain的支持,已有一段时间了。
答案 0 :(得分:0)
我正在使用mixin在一个视图集上允许多个序列化器。
class MultiSerializerMixin(object):
def get_serializer_class(self):
if self.action in self.serializers:
return self.serializers.get(self.action, None)
else:
return super(MultiSerializerMixin, self).get_serializer_class()
我在视图集中包括了一个字典,以确定要使用哪个序列化器
serializers = {
'list': CustomerListSerializer,
'retrieve': CustomerDetailSerializer,
'update': CustomerDetailSerializer,
'partial_update': CustomerDetailSerializer,
}
OPTIONS
请求使用基本元数据类SimpleMetadata
。调用SimpleMetadata().determine_actions()
时,串行器由view.get_serializer()
确定,它返回了错误的串行器,并为我提供了GET
而不是PUT
的所有操作。