-->

Django-models: use field from foreign key

2019-07-14 20:05发布

问题:

I'm working on an image gallery project in DJango, just for the sake of it. And well, I have a class named Gallery and a class named ImageGallery.

The class named gallery would look like this:

class Gallery(models.Model):
 gallery = models.ForeignKey(Gallery, related_name="parent_gallery")
 title = models.CharField(max_length=200)
 folder = models.CharField(max_length=200) # ex: images/galleries/slugify(self.title)

class ImageGallery(models.Model):
 gallery = models.ForeignKey(Gallery, related_name="parent_gallery")
 title = models.CharField(max_length=200)
 image = models.ImageField(upload_to=self.gallery.folder)

Well, the last line of code is what I want to know if its possible or any other fine replacement for it.

In the DJango-admin I want to be able to add records for the table ImageGallery and when selecting the Gallery I would like to use, the images to be saved to the folder specified in gallery.folder field.

What's the best way to go around this? I haven't completed writing the two classes but I doubt they're gonna work like this. Thank you in advance. :-)

回答1:

The FileField.upload_to is defined as follows

This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method. ... upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are:

But self.gallery.folder isn't a callable. What you need is to setup a function along the lines given in that example

def get_upload_path(instance, filename):
    return '{0}/{1}'.format(instance.gallery.folder, filename)

And your model will change to

image = models.ImageField(upload_to=get_upload_path)