在我的Django应用程序(使用drf)中,我已经修改了模型的序列化器以获取前端所需的输入,但是运气不好,试图将此序列化器嵌套在另一个序列化器中。
我尝试使用to_representation方法创建模型的字段并放置get_photos方法,但这些都不是什么。
# models.py
class Photo(models.Model):
photo = models.OneToOneField(RawPhoto, related_name='contest_photo', on_delete=models.CASCADE)
thumbnail_size = models.OneToOneField(PhotoSize, related_name='contest_photo', on_delete=models.CASCADE)
thumbnail_url = models.TextField(verbose_name='thumbnail_url')
class Meta:
verbose_name = 'Contest Photo'
@property
def get_photo_src(self):
return settings.MEDIA_URL + self.photo.image.name
@property
def get_thumbnail_url(self):
# dont forget to add cache
if len(self.thumbnail_url) == 0:
file_name = self.get_photo_src
last_dot = file_name.rfind('.')
photo_name, photo_extension = file_name[:last_dot], file_name[last_dot:]
self.thumbnail_url = photo_name + '_' + self.thumbnail_size.name + photo_extension
return self.thumbnail_url
# serializers.py
class PhotoSerializer(serializers.ModelSerializer):
thumbnail_height = serializers.ReadOnlyField(source='thumbnail_size.height')
thumbnail_width = serializers.ReadOnlyField(source='thumbnail_size.width')
src = serializers.ReadOnlyField(source='get_photo_src')
thumbnail_url = serializers.ReadOnlyField(source='get_thumbnail_url')
caption = serializers.ReadOnlyField(source='photo.caption')
class Meta:
model = Photo
fields = ['src', 'thumbnail_url', 'thumbnail_height', 'thumbnail_width', 'caption']
class GallerySerializer(serializers.ModelSerializer):
photos = PhotoSerializer(many=True)
class Meta:
model = Gallery
fields = ['title', 'photos']
PhotoSerializer实际上返回了我期望它得到的对象的完整描述,但是当我将其嵌套在GallerySerializer中时,它仅显示thumbnail_url,这是模型本身包含的唯一字段。 无论如何,我可以在GallerySerializer中包含PhotoSerializer的字段吗? (应该是照片列表)
谢谢。
答案 0 :(得分:1)
使用here
所述的depth自变量class GallerySerializer(serializers.ModelSerializer):
photos = PhotoSerializer(many=True)
class Meta:
depth=1
model = Gallery
fields = ['title', 'photos']