saving files based on db field

Hi
I have a model “Products” that saves files to specific directory

class Product(models.Model):
name = models.CharField(max_length=500, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=True, null=False)
digital = models.BooleanField(default=True, null=True, blank=False)
video_name= models.CharField(max_length=500)
price = models.FloatField(null=True, blank=False)
image = models.ImageField(upload_to=‘images/’,null=True, blank=True)
video_file= models.FileField(upload_to=‘videos/’, null=True, verbose_name="")

as you can see the last field has upload to specific directory. In the model there is “category” field, i need to save files based on the choice of which category.

example: if category is “food” then the files will be saved videos/food/…

Thanks

See the docs for the upload_to attribute. You can set that to be a function that will return the path at the time when it’s needed.

I have this example:

def generate_filename(self, instance, filename):
    directory_name = os.path.normpath('videos/') # here i want to add the category name
    return os.path.join(directory_name, self.get_filename(filename))

class Page(models.Model):
    title = models.CharField(max_length=20)
    app = models.ForeignKey(App)
    file = model.FileField(upload_to=generate_filename)

the class is in models.py but not sure where to put the function above that? is it in the file that i am adding the video (90% sure it is) or the same models.py file? How to add the category name after it is chosen?

one more thing,

Since the model is the only object calling that function, you can put it in the models.py file.

But to be more accurate - it’s no different than any other function. It could be placed anywhere, and imported from that other file into your models.py

Look at the example in the docs. It shows how it’s referencing another field in the same model.