tags:

views:

65

answers:

2

Hello, I have the two models shown below:

class EntryImage(models.Model):  
    image = models.ImageField(upload_to="entries")

class Entry(models.Model):  
    code = models.CharField(max_length=70, unique=True)  
    images = models.ManyToManyField(EntryImage, null=True, blank=True)

As you can see, Entry can have 0 or more images. My question is: Is it possible to have that kind of schema and dynamically change the upload_to based on the Entry code?

A: 

You can make upload_to a callable, in which case it will be called and passed the instance of the model it is on. However, this may not have been saved yet, in which case you may not be able to query the Entry code.

Daniel Roseman
Thanks for the quick answer. What would be an alternative schema for having: 1 Entry that has many images and those images are uploaded to a specific directory? (Since I have MANY entries I wouldn't prefer having a foreign key in EntryImage pointing to Entry)
dimitris
A: 

Well without going too far off, you could make an intermediary M2M table EntryImageDir with the directory name in it. You would link your EntryImages there with a foreign key and you could create the EntryImageDir either with a signal on Entry create or when uploading something.

The documentation for M2M with custom fields is here: http://www.djangoproject.com/documentation/models/m2m_intermediary/

alper