Django - 如何获取与另一个字段相关的upload_to目录

时间:2018-04-04 18:11:07

标签: python django database models

我认为代码不言而喻。我有2个模型 - 食物和类别,我想将食物图像保存到与食物类别同名的文件夹中。我在想我可能会覆盖保存方法,但我无法弄清楚如何使它工作。有什么想法吗?

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=255)
    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'Categories'

class Food(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category, on_delete='CASCADE')
    image = models.ImageField(upload_to='{}'.format(category.name))

    def __str__(self):
        return self.name

1 个答案:

答案 0 :(得分:2)

Django文档说 upload_to 也可以是可调用的,例如函数。您可以查看更多详细信息here

对于您的用例,它应该是这样的:

def food_path(instance, filename):
    return '{0}/{1}'.format(instance.category.name, filename)

class Food(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category, on_delete='CASCADE')
    image = models.ImageField(upload_to=food_path)

    def __str__(self):
        return self.name