DRF-NestedSerializer的SerializerMethodField

时间:2019-01-14 16:01:44

标签: django django-rest-framework django-serializer

我有一个序列化器,如下所示:-

class ABCSerializer(serializer.ModelSerializer):

    class XYZSerializer(serializers.Serializer):

        a = serializers.CharField(default='abcd') #Try1:- Setting default values.
        b = serializers.IntegerField(default=1)
        c = serializers.ListField(default=[''])

        def get_attribute(self, instance): # Try 2. This works only when many != True.
            return [
            {
            'a': 'abcd',
            'b': 1,
            'c': []
            }]

    field1 = XYZSerializer(many=True)

    def get_field1(self, instance):  # Try 3
        return [
            {
            'a': 'abcd',
            'b': 1,
            'c': []
            }
        ]

    class Meta:
        fields = ('uuid', 'field1')
        extra_kwargs = {
            'uuid': {'source': 'user_id'}
        }

我想返回默认值XYZSerializer。我该怎么办?

我尝试覆盖get_attribute中的XYZSerializer,但是仅在many != True时有效。我也尝试过get_field1,但无济于事。

如何传递默认值XYZSerializer

0 个答案:

没有答案