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?
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/
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.
精彩评论