Hello everyone,
I'm working with a model that has an associated image, I'd like to organise my media folder like this: media/my_model/{instance.id}/my_model_icon/{filename}
def model_icon_upload_path(instance, filename):
return f"my_model/{instance.id}/my_model_icon/{filename}"
class MyModel(models.Model):
name = models.CharField(max_length=30)
icon = models.FileField(upload_to=model_icon_upload_path, blank=True, null=True)
The problem is that the instance.id will be None when creating a new instance.
One approach would be to save the instance temporarily, then rename the folder path and the file field in the instance, but I don't like this solution (I want one single SQL query)
So is there a good way in Django to achieve the desired path structure (something like getting the next available id for the new instance before saving it and making a lock until the instance is saved, assuming this approach is considered acceptable)?