使用Django rest
以下是我的serializer.py的显示方式。
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('id', 'name', 'active', 'type')
类型是平面 View
然后,我对其进行了更改,因此像这样为每个配置文件嵌套了“类型” ...
class TypeSerializer(serializers.ModelSerializer):
class Meta:
model = Type
fields = ('id', 'name', 'active')
class ProfileSerializer(serializers.ModelSerializer):
type = TypeSerializer()
class Meta:
model = Profile
fields = ('id', 'name', 'active', 'type'')
现在这可以完美地工作,但是现在我只能在个人资料详细信息中将其更新为只读时才更新“类型”。
创建新的配置文件时如何添加类型并仍然保留此嵌套 View ?
我希望我已经清楚地解释了这一点。
更新:
好的,我读到以下内容:
Note: Nested serializers are only suitable for read-only representations, as there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. For read-write representations you should always use a flat representation, by using one of the RelatedField subclasses.
因此,这是有道理的。所以我将其更改为...
type = serializers.PrimaryKeyRelatedField()
这就把它放回POST并可以工作了,但是很遗憾,我不能用ID和名称来表示“类型”,所以对最终用户更有意义吗?
最佳答案
jQueryt_a是对可写嵌套序列化程序的完全支持,但与此同时,一种解决方案是在每种情况下都在 View 中覆盖create
方法:
class FooListCreateView(ListCreateAPIView):
model = Foo
serializer_class = FooSerializer
def create(self, request, *args, **kwargs):
data=request.DATA
f = Foo.objects.create()
# ... create nested objects from request data ...
# ...
return Response(serializer.data,
status=status.HTTP_201_CREATED,
headers=headers)
可能不是理想的,但是它对我有用,直到采取正确的方法为止。
关于Django REST : Nested object add on create (POST) not just update (PUT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14978464/