简体   繁体   中英

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(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM