在嵌套的序列化程序字段中访问序列化程序实例

Moy*_*lin 4 python django django-rest-framework

嵌套序列化程序中的字段内部是否存在访问父序列化程序实例的方法.特别是在列表视图中访问的实例,尤其是最顶层序列化程序可能具有多个实例的情况.我想将此作为上下文传递,但上下文由视图传递.

在字段的to_representation中,例如,在列表中,我可以访问列表视图中父项的实例列表,但我不确定哪个是当前正在处理的实例.

mik*_*725 10

这个问题有点过于宽泛,所以我会给出一个通用的答案.

DRF中的任何字段(包括序列化器,因为它们从字段中继承)可以通过访问父序列化程序self.parent.此外,您还可以通过访问根序列化程序本身(在视图中实例化的序列化程序)self.root.

但是,根据我在你的问题中收集到的内容,你正在尝试在执行过程中从父序列化程序访问某些状态to_representation.这样做很滑,因为在DRF中,序列化和验证都是无状态过程.换句话说,只有根序列化程序可以具有状态(存储状态打开self),但不应该在子序列化程序中发生.如果需要访问状态,最好的方法是在序列化器之间显式传递状态.例如:

class ChildSerializer(Serializer):
    def to_representation(self, instance):
        foo = instance.foo  # comes from parent serializer
        ...

class RootSerializer(Serializer):
    child = ChildSerializer()
    def to_representation(self, instance):
        instance.foo = 'foo'  # parent is setting state
        ...
Run Code Online (Sandbox Code Playgroud)

您还提到您正在使用列表.ListSerializer如果你需要在那里传递状态并因此创建一个自定义,那将涉及到s ListSerializer:

class RootListSerializer(ListSerializer):
    def to_representation(self, instance):
        for i in instance:
            i.foo = 'foo'
        ...

class RootSerializer(Serializer):
    class Meta(object):
        list_serializer_class = RootListSerializer
Run Code Online (Sandbox Code Playgroud)