Reputation: 31
In my Django app (using drf), I've modified my model's serializer to get the front-end's desired input, but I'm having zero luck trying to nest this serializer inside another one.
I've tried creating a field of the model with the to_representation method and putting a get_photos method, none of which amounted to anything.
# 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 actually returns the full description of the object that I expect from it, but when I nest it inside GallerySerializer, it only shows thumbnail_url, which is the only field that is included in the model itself. Is there anyway I can include PhotoSerializer's fields inside GallerySerializer? (which is supposed to be a list of Photos)
Thanks.
Upvotes: 1
Views: 134
Reputation: 2157
use the depth argument as described here
class GallerySerializer(serializers.ModelSerializer):
photos = PhotoSerializer(many=True)
class Meta:
depth=1
model = Gallery
fields = ['title', 'photos']
Upvotes: 2