I have a model PhotoAlbum:
class PhotoAlbum(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, auto_created=True)
name = models.CharField(max_length=50)
And i need to store a list of photos, and when i send a GET request i should see the photos in the format like:
GET /albums
{
'id': 'randomUUID',
'name' : 'MyAlbum'
'photos': [
{
"id": "randomUUID",
"image": "photo.jpg",
},
{
"id": "randomUUID",
"name": "photo2.jpg",
}
]
}
So, to realize this i want to create 2 more models:
class Image(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, auto_created=True)
image = models.ImageField(upload_to='media/')
class AlbumImage(models.Model):
album = models.ForeignKey(PhotoAlbum, on_delete=models.CASCADE)
image = Image()
And create two serializers: for PhotoAlbum, and for Image (to show url).
Is it good solution to solve this task? Can you offer the more optimal?
>Solution :
A slightly better solution may be to use a serializer that can handle both models, so you don’t need to create two separate serializers. You can use a ModelSerializer so:
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = AlbumImage
fields = ['id', 'image']
class PhotoAlbumSerializer(serializers.ModelSerializer):
photos = ImageSerializer(many=True)
class Meta:
model = PhotoAlbum
fields = ['id', 'name', 'photos']
Now, you need to use PhotoAlbumSerializer to serialize the data and then return the response.