Search code examples
pythondjangodatabasemodels

Django - how to get upload_to directory related to another field


I think the code speaks for itself. I have 2 models - Food and Category and I want to save the food images to a folder that has the same name as the category of the food. I was thinking that I could possibly override the save method but I can't figure out how to make it work. Any ideas?

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

Solution

  • Django documentation says that upload_to may also be a callable, such as a function. You can see more details here.

    For your use-case it should be something like this:

    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