serializer.data缺少一些数据

时间:2017-04-13 22:20:28

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

上下文:我在访问由嵌套序列化程序验证的字段时遇到问题。 我有一个非常样本的模型,如下所示。 对于其中两个字段,我有他们特定的序列化器。当我尝试访问数据时,它返回除特定序列化程序验证的字段之外的所有字段。

模型看起来像这样

class Sampler(models.Model):
  sample_name = models.CharField(unique=True, max_length=100)
  sampling_by = JSONField(max_length=100)
  extractions = JSONField(max_length=100)
  max_samples = models.IntegerField(default=100)

串行器

class ExtractionsSerializer(serializers.BaseSerializer):
   table_name = serializers.CharField()
   extraction_type = serializers.ChoiceField(["ABC"])
   dependencies = serializers.ListField(child=RecursiveField(), allow_empty=True, required=False)


class SamplingBySerializer(serializers.BaseSerializer):
"""
    Validate sampling_by
"""
    def to_internal_value(self, samples):
      methods = ["ABC"]
      sampling_not_supported = [sample for sample in samples
                              if sample['by'] not in methods]
       if sampling_not_supported:
          raise ValidationError("{} not in {}".format(sampling_not_supported, methods))

class SamplerSerializer(serializers.ModelSerializer):
    extractions = ExtractionsSerializer(read_only=True)
    sampling_by = SamplingBySerializer(read_only=True)

    class Meta:
      model = Sampler
      fields = ('sample_name', 'database', 'schema', 'sampling_by', 'extractions', 'max_samples')

现在我做

data = {
"database": "postgresql://..",
"sampling_by":[{
    "by":"ABC",
    "value": ["l32=turn_the"]
}],
"max_samples":3,
"extractions" : [{
    "table_name": "person", 
    "extraction_type": "ABC"
}]
}
sampler = SamplerSerializer(data=data)
sampler.is_valid() #returns True
sampler.data => does not contain data of the nested fields. Like the `sampling_by` and `extractions`. Contains all other fields
sampler.validated_data => same problem as above

任何帮助将不胜感激!感谢

1 个答案:

答案 0 :(得分:0)

您可能错过了嵌套序列化程序标记为read_only=True

的事实
class SamplerSerializer(serializers.ModelSerializer):
    extractions = ExtractionsSerializer(read_only=True)
    sampling_by = SamplingBySerializer(read_only=True)

删除该部分,实施序列化程序create / update,您就可以了。

另一方面,反序列化时访问serializer.data没有意义。

编辑:权限来源为validated_data