How do I reference the other object in django models
first post here.In Django, I want to have many files be associated with a particular model, so I'm doing a seperate model called files and have model 'A' 'have many' files. But I want my files to be saved in director named by model 'A'. So For example I want something like this:
class Show(models.Model):
name = models.CharField()
showfolder = models.FilePathField()
class Episode(models.Model):
show = models.ForeignKey(Show)
name = models.CharField()
files = models.ManyToManyField(mp3)
class Mp3开发者_如何学C(models.Model):
file = FileField(upload_to=Episode.show.showfolder)
So hopefully that last line expresses what I WANT it to do(get the folder name from Show object associated with the episode). The question is how would I really write that?(besides jumping through hoops in the controller.)
Thanks.
In your current model because of Episode ManyToMany relation to Mp3 it is possible for one file to be associated with one or more episodes. That would mean that your file will have to simultaneously exist in several locations.
To have a hierarchical structure you need ForeignKey to Episode in Mp3 model:
class Mp3(Model):
episode = ForeignKey(Episode)
Now about your file name. According to django documentation, upload_to
attribute can accept callable and will pass two arguments to it: instance
and filename
.
def get_file_name(instance, original_filename):
return os.path.join(MEDIA_ROOT, 'mp3', instance.episode.show.showfolder,
original_filename)
class Mp3(Model):
file = FileField(upload_to=get_file_name)
精彩评论