I need to get the id (pk) of a related model.foreignKey object in order to set the "upload_to" attr of a model.FileField of the same model.
Something like this:
class myClass(models.Model):
related_model = models.ForeignKey(RelatedModel,on_delete=models.CASCADE)
file = models.FileField(upload_to=str(related_model.id)+"/")
So for example, if the related_model has the primary_key 10 the upload_to attr has to be "10/"
It is possible or I have to set that value in the view.py file when the object is created?
Use a callable as the upload_to
parameter.
def related_path(instance, filename):
return '{}/{}'.format(instance.related_model_id, filename)
class myClass(models.Model):
related_model = models.ForeignKey(RelatedModel,on_delete=models.CASCADE)
file = models.FileField(upload_to=related_path)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.