Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

DB Architecture to store list of images

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
   '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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading