Django-models:使用来自外键的字段
Django-models: use field from foreign key
我正在 DJango 中从事一个图片库项目,只是为了它。好吧,我有一个名为 Gallery
的 class 和一个名为 ImageGallery
的 class。
class 命名的图库如下所示:
class Gallery(models.Model):
gallery = models.ForeignKey(Gallery, related_name="parent_gallery")
title = models.CharField(max_length=200)
folder = models.CharField(max_length=200) # ex: images/galleries/slugify(self.title)
class ImageGallery(models.Model):
gallery = models.ForeignKey(Gallery, related_name="parent_gallery")
title = models.CharField(max_length=200)
image = models.ImageField(upload_to=self.gallery.folder)
好吧,最后一行代码是我想知道的,如果它可能或任何其他好的替代品。
在 DJango-admin
中,我希望能够为 table ImageGallery
添加记录,并且在选择 Gallery
我想使用的图像时保存到 gallery.folder
字段中指定的文件夹中。
解决这个问题的最佳方法是什么?我还没有完成这两个 classes 的编写,但我怀疑它们是否会像这样工作。先感谢您。 :-)
This attribute provides a way of setting the upload directory and file
name, and can be set in two ways. In both cases, the value is passed
to the Storage.save() method. ... upload_to may also be a callable,
such as a function. This will be called to obtain the upload path,
including the filename. This callable must accept two arguments and
return a Unix-style path (with forward slashes) to be passed along to
the storage system. The two arguments are:
但是 self.gallery.folder
不是可调用的。您需要的是按照该示例中给出的行设置一个函数
def get_upload_path(instance, filename):
return '{0}/{1}'.format(instance.gallery.folder, filename)
您的模型将变为
image = models.ImageField(upload_to=get_upload_path)
我正在 DJango 中从事一个图片库项目,只是为了它。好吧,我有一个名为 Gallery
的 class 和一个名为 ImageGallery
的 class。
class 命名的图库如下所示:
class Gallery(models.Model):
gallery = models.ForeignKey(Gallery, related_name="parent_gallery")
title = models.CharField(max_length=200)
folder = models.CharField(max_length=200) # ex: images/galleries/slugify(self.title)
class ImageGallery(models.Model):
gallery = models.ForeignKey(Gallery, related_name="parent_gallery")
title = models.CharField(max_length=200)
image = models.ImageField(upload_to=self.gallery.folder)
好吧,最后一行代码是我想知道的,如果它可能或任何其他好的替代品。
在 DJango-admin
中,我希望能够为 table ImageGallery
添加记录,并且在选择 Gallery
我想使用的图像时保存到 gallery.folder
字段中指定的文件夹中。
解决这个问题的最佳方法是什么?我还没有完成这两个 classes 的编写,但我怀疑它们是否会像这样工作。先感谢您。 :-)
This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method. ... upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are:
但是 self.gallery.folder
不是可调用的。您需要的是按照该示例中给出的行设置一个函数
def get_upload_path(instance, filename):
return '{0}/{1}'.format(instance.gallery.folder, filename)
您的模型将变为
image = models.ImageField(upload_to=get_upload_path)