【问题标题】:Django - upload_to dynamic path from different modelsDjango - 来自不同模型的upload_to动态路径
【发布时间】:2020-04-10 08:00:11
【问题描述】:

我正在尝试使用 ImageField upload_to 以有组织的方式保存图像,但我不知道这是否可行或如何。 我正在尝试在媒体中使用此文件夹层次结构:

Book-title
    Chapter 1
        img1
        img2
    Chapter 2
        img1

型号:

class Book(models.Model):
    title = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    author = models.ManyToManyField(Author)
    chapter = models.ManyToManyField(Chapter, related_name='books')
def image_dir_path(instance, filename):
    chapter = instance.slug
    return os.path.join(chapter, filename)


class Chapter(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=130, unique=True)
    slug = models.SlugField(max_length=150, unique=True, blank=True)
    picture = models.ImageField(upload_to=image_dir_path)
    created_at = models.DateField(auto_now_add=True)

我想要这样的东西,所以我可以使用书名来构建路径:

def image_dir_path(instance, filename):
    book = instance.book.slug
    chapter = instance.slug
    return os.path.join(book, chapter, filename)

这不起作用,例如它仅与您调用image_dir_path的类有关。

可能是类似的东西吗?

【问题讨论】:

    标签: django python-3.x django-models django-3.0


    【解决方案1】:

    我发现的一种解决方法是在Chapter 中调用Book,建立“OneToMany”关系。 不需要 ManyToMany。

    def image_dir_path(instance, filename):
        book = instance.book.slug
        chapter = instance.slug
        return os.path.join(book, chapter, filename)
    
    
    class Chapter(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
        book = models.ForeignKey(
                Book,
                related_name='chapters',
                on_delete=models.CASCADE,
                default=''
        )    
        title = models.CharField(max_length=130, unique=True)
        slug = models.SlugField(max_length=150, unique=True, blank=True)
        picture = models.ImageField(upload_to=image_dir_path)
        created_at = models.DateField(auto_now_add=True)
    

    【讨论】:

      猜你喜欢
      • 2012-03-01
      • 2013-07-06
      • 2018-11-08
      • 2018-02-25
      • 2018-01-03
      • 2016-05-24
      • 2019-04-14
      • 2013-06-24
      • 2023-03-18
      相关资源
      最近更新 更多