gpt4 book ai didi

django - DRF ListSerializer 和 ListField

转载 作者:行者123 更新时间:2023-12-02 14:58:41 26 4
gpt4 key购买 nike

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

在此之前,我的代码运行良好,没有任何错误和不当行为。现在我使用 ListField 作为我的列表字段序列化器,但是我不知道什么时候使用 ListSerializer?有人可以解释 ListSerializer 和 FieldSerializer 之间的区别吗?

我使用 ListSerializer 的示例代码:

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

我的 ListField 示例代码:

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

最佳答案

免责声明:此答案不完整

Can someone explain the difference between ListSerializer and FieldSerializer?

我假设问题是 serializers.ListSerializerserializers.ListField 之间的区别

假设我们有两个模型作为

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}'

序列化器作为

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
如官方所述DRF doc

When a serializer is instantiated and many=True is passed, a ListSerializer instance will be created. The serializer class then becomes a child of the parent ListSerializer

例如,我们可以用 ListSerializer 重写 MusicianSerializer

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


查看源码时,发现ListSerializerListField都是继承自同一个类(父类和祖父类相同)

关于django - DRF ListSerializer 和 ListField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51489952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com