Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 938
Michal Strnad Avatar asked Oct 15 '25 21:10

Michal Strnad


1 Answers

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
like image 90
T.Tokic Avatar answered Oct 18 '25 10:10

T.Tokic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!