关于python:django中的Cloudinary多图像上传?

Cloudinary multiple image upload in django?

我有一个图片上传定义如下在我的django应用程序与cloudinary包,

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

我想让这个领域上传多个图像。我该怎么做?


包含多个图像的照片将成为相册或照片库。我将改造如下:

1
2
3
4
5
6
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')

使用实例:

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

现在,Photo知道它的PhotoAlbum

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

PhotoAlbum跟踪所有Photo的:

1
2
3
4
5
6
7
8
9
>>> 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

我会这样做的:

1
2
3
4
5
class Photo(models.Model):
    photos = models.ManyToManyField('ChildPhoto',blank=True)

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

你可以上传很多照片,照片模型会有很多照片到儿童照片模型。