Charalampos B.
Charalampos B.

Reputation: 13

How to access the __str__ method of a model via a ForeignKey?

I have created a File model and a Folder model. The File model is connected to the Owner (User) and a Folder via a Foreign key. Now I want to upload the file at the path: owner_username/folder_title. My question is how to access the __str__method of the Folder model using the ForeignKey, from inside the File Model ?

My guess was to set at the FileField the argument upload_to equal tostr(folder)but as a result my file was uploaded at:<django.db.models.fields.related.ForeignKey>/graph2.jpg

at models.py:

class Folder(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length = 20)

    def __str__(self):
        return self.title

class File(models.Model):
    owner = models.ForeignKey(User, related_name='user', 
                               on_delete=models.CASCADE)
    folder = models.ForeignKey(Folder, related_name = 'files', 
                                on_delete=models.CASCADE, default="")
    file = models.FileField(upload_to = !!!!?ownername/foldername?!!!!)

    def __str__(self):
        return str(self.file)

I expect somehow to upload the file at the path that has the following format: nameOfTheOwner/nameOfTheFolder

Upvotes: 1

Views: 392

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

You can make set the upload_to= parameter [Django-doc] to a callable that has access to the self, like:

class File(models.Model):

    def gen_filename(self, filename):
        return '{}/{}/{}'.format(self.owner.username, self.folder.title, filename)

    owner = models.ForeignKey(
        User,
        related_name='user', 
        on_delete=models.CASCADE
    )
    folder = models.ForeignKey(
        Folder,
        related_name='files', 
        on_delete=models.CASCADE,
        default=''
    )
    file = models.FileField(upload_to=gen_filename)

    def __str__(self):
        return str(self.file)

or you can make use of the __str__ of the folder, like:

class File(models.Model):

    def gen_filename(self, filename):
        return '{}/{}/'.format(self.owner.username, self.folder, filename)

    owner = models.ForeignKey(
        User,
        related_name='user', 
        on_delete=models.CASCADE
    )
    folder = models.ForeignKey(
        Folder,
        related_name='files', 
        on_delete=models.CASCADE,
        default=''
    )
    file = models.FileField(upload_to=gen_filename)

    def __str__(self):
        return str(self.file)

Upvotes: 2

Related Questions