简体   繁体   English

如何在Django模型中引用其他对象

[英]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. 在Django中,我希望有许多文件与特定模型关联,因此我正在做一个单独的模型,称为文件,并且模型“ A”“有很多”文件。 But I want my files to be saved in director named by model 'A'. 但我希望将文件保存在型号为“ 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). 因此,希望最后一行表示我想要执行的操作(从与该情节关联的Show对象获取文件夹名称)。 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. 在当前模型中,由于与MP3有关的Episode ManyToMany关系,一个文件可能与一个或多个情节相关联。 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: 要具有层次结构,您需要在Mp3模型中使用ForeignKey插入Episode:

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 . 根据django文档upload_to属性可以接受callable并将其传递两个参数: instancefilename

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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