Search code examples
djangoforeign-keysdjango-file-upload

Set ``upload_to`` function of a field in a foreign key


I have the following models structure:

class BaseMovie(models.Model):
    movie = models.FileField('Movie')
    width = models.IntegerField('Width')
    height = models.IntegerField('Height')
    duration = models.FloatField('Duration')

class SpecialMovie(models.model):
    base_movie = models.ForeignKey(BaseMovie, 'Base movie')
    # some other stuff

The idea behind is that I intend to use BaseMovie in several models.

My question is:

How can I set, in the SpecialMovie model, the location to which the special movies will be uploaded?

I think that storing only the metadata in the BaseMovie class and having the movie field with appropriate upload_to function in the SpecialMovie is not satisfying, because I would have to copy the code that fills the metadata in all the models with a foreign key to BaseMovie.


Solution

  • upload_to can be a callable; you could set it to a function that checks if the instance has a related SpecialMovie, and return the correct value accordingly.