4

I have an image upload defined as follows in my Django app with Cloudinary package,

class Photo(models.Model):
    photo = CloudinaryField('image')

I Would like to make this field upload mutliple images. How do I do this?

All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111

2 Answers2

6

A photo holding multiple images becomes a photo album, or a photo gallery. I'd remodel al follows:

class PhotoAlbum(models.Model):
    name = models.CharField()  # or whatever a photo album has

class Photo(models.Model):
    file = CloudinaryField('image')
    album = models.ForeignKey(PhotoAlbum, on_delete=models.CASCADE, related_name='photos')

Usage example:

>>> album = PhotoAlbum.objects.create(name='myalbum')
>>> photo = Photo.objects.create(album=album, image=...)

Now, the Photo knows its PhotoAlbum:

>>> photo = Photo.objects.first()
>>> photo.album
<PhotoAlbum: myalbum>

The PhotoAlbum keeps track of all the Photos:

>>> album = PhotoAlbum.objects.first()
>>> album
<PhotoAlbum: myalbum>
>>> album.photos.all()
<QuerySet [<Photo: Photo-1>]>
>>> album == Photo.objects.first().album
>>> True
>>> Photo.objects.first() == album.photos.first()
>>> True
hoefling
  • 59,418
  • 12
  • 147
  • 194
3

I'd do it like that:

class Photo(models.Model):
    photos = models.ManyToManyField('ChildPhoto',blank=True)

class ChildPhoto(models.Model):
    photo = CloudinaryField('image')

You can upload many photos and the Photo model will have a manytomany to the ChildPhoto model

Lemayzeur
  • 8,297
  • 3
  • 23
  • 50