我在我的带有Cloudinary包的Django应用程序中定义了如下图像上传,
class Photo(models.Model):
photo = CloudinaryField('image')
我想让这个字段上传多个图像。我该怎么做呢?
答案 0 :(得分:5)
包含多张图片的照片会成为相册或照片库。我改造了以下内容:
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')
用法示例:
>>> album = PhotoAlbum.objects.create(name='myalbum')
>>> photo = Photo.objects.create(album=album, image=...)
现在,Photo
知道其PhotoAlbum
:
>>> photo = Photo.objects.first()
>>> photo.album
<PhotoAlbum: myalbum>
PhotoAlbum
会跟踪所有Photo
s:
>>> 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)
我会这样做:
class Photo(models.Model):
photos = models.ManyToManyField('ChildPhoto',blank=True)
class ChildPhoto(models.Model):
photo = CloudinaryField('image')
您可以上传许多照片,而照片模型将与ChildPhoto模型相比具有更多优势