从django rest framework serializer中排除一个字段

时间:2021-11-11 19:34:21

In the following serializer, I have a nested serializer [ContainerSerializer] field and I want to exclude a field from (container)ContainerSerializer but I don't want any change in ContainerSerializer. How can I do that?

在下面的序列化程序中,我有一个嵌套的序列化程序[ContainerSerializer]字段,我想从(容器)ContainerSerializer中排除一个字段,但我不想在ContainerSerializer中进行任何更改。我怎样才能做到这一点?

class BLcontainerMergedSerializer(serializers.ModelSerializer):
    container = ContainerSerializer()
    class Meta:
        model = BLcontainer

2 个解决方案

#1


7  

Create another serializer say BLContainerSerializer and exclude fields there. Then use this in your BLcontainerMergedSerializer. Hope this helps.

创建另一个序列化程序说BLContainerSerializer并在那里排除字段。然后在BLcontainerMergedSerializer中使用它。希望这可以帮助。

class BLContainerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Container
        exclude = ('field1', )


class BLcontainerMergedSerializer(serializers.ModelSerializer):
    container = BLContainerSerializer()
    class Meta:
        model = BLcontainer

#2


5  

There is a fields meta property:

有一个字段元属性:

class BLcontainerMergedSerializer(serializers.ModelSerializer):
    container = ContainerSerializer()
    class Meta:
        model = BLcontainer
        fields = ('field1', 'field2')

Reference: Django REST docs

参考:Django REST文档

#1


7  

Create another serializer say BLContainerSerializer and exclude fields there. Then use this in your BLcontainerMergedSerializer. Hope this helps.

创建另一个序列化程序说BLContainerSerializer并在那里排除字段。然后在BLcontainerMergedSerializer中使用它。希望这可以帮助。

class BLContainerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Container
        exclude = ('field1', )


class BLcontainerMergedSerializer(serializers.ModelSerializer):
    container = BLContainerSerializer()
    class Meta:
        model = BLcontainer

#2


5  

There is a fields meta property:

有一个字段元属性:

class BLcontainerMergedSerializer(serializers.ModelSerializer):
    container = ContainerSerializer()
    class Meta:
        model = BLcontainer
        fields = ('field1', 'field2')

Reference: Django REST docs

参考:Django REST文档