So, assume I have the following (simplified) Django model:
class Document(models.Model):
def get_file_path(self, filename):
extension = filename.split('.')[-1]
product_string = ', '.join(p.__str__() for p in self.related_products.all())
return 'documents/{}/{}.{}'.format(product_string, self.document_id, extension)
document_id = models.CharField(max_length=9)
related_products = models.ManyToManyField(to=Product, related_name='documents')
file = models.FileField(upload_to=get_file_path)
As you can see I want my filepath based on the contents of the m2m (related_products) relationship. This doesn't work though, and throws the following error:
needs to have a value for field "id" before this many-to-many relationship can be used.
Which of course makes sense. But, I don't know how to solve it. I either need access to the m2m relationship information before it's saved. Or, I need to save the model and its relationships first without saving the file, and only then save the file specifically.
Also, if it matter; this only has to work in the Django Admin.
Any help would be appreciated. Thanks! :)