DRF ListSerializer和FieldSerializer

时间:2018-07-24 03:16:39

标签: django django-rest-framework serializer

我在项目中使用django rest,直到现在为止我使用ListSerializer的对象列表,当我需要具有列表的最小长度和最大长度时,我用谷歌搜索并达到了ListField

在我的代码工作正常之前,没有任何错误和不当行为。现在,我将ListField用于列表字段序列化程序,但是我什么时候不使用ListSerializer?有人可以解释ListSerializer和FieldSerializer之间的区别吗?

使用ListSerializer的示例代码:

tags = serializers.ListSerializer(child=serializers.CharField(allow_blank=False), required=False)

我与FieldSerialzier一起使用的示例代码:

open_hour = serializers.ListField(child=serializers.DictField(), max_length=7, min_length=7)

1 个答案:

答案 0 :(得分:1)

免责声明:此答案不完整

  

有人可以解释ListSerializer和   FieldSerializer?

我认为问题是Shim shim = Shim.Replace(() => StaticClass.GetFile(Is.A<string>())) .With((string name) => /*Here return your mocked value for test*/); var sut = new Service(); PoseContext.Isolate(() => result = sut.foo("filename") /*Here the foo will take your mocked implementation of GetFile*/, shim); serializers.ListSerializer之间的差异


假设我们有两个serializers.ListField作为

models

class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) def __str__(self): return f'{self.first_name} {self.last_name}' class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField() def __str__(self): return f'{self.name} : {self.artist}'

serializer



ListSerializer
如官方DRF doc

中所述
  

实例化序列化程序并传递class AlbumSerializer(serializers.ModelSerializer): artist = serializers.StringRelatedField() class Meta: fields = '__all__' model = Album class MusicianSerializer(serializers.ModelSerializer): AlbumSerializer(many=True, source='album_set') class Meta: fields = '__all__' model = Musician 时,   将创建ListSerializer实例。然后,序列化器类   成为父ListSerializer的many=True

例如,我们可以使用childMusicianSerializer重写为

ListSerializer

它将产生与以前相同的结果。但是,如果我们尝试使用class MusicianSerializer(serializers.ModelSerializer): albums = serializers.ListSerializer(child=AlbumSerializer(), source='album_set') class Meta: fields = '__all__' model = Musician 而不是ListField,它将引发错误

ListSerializer


在检查源代码时,我发现'RelatedManager' object is not iterable ListSerializer都是从同一个类继承的(父代和祖父母是相同的)