'Is there any way to alter the url of a FileField in Django?
FileField objects have a url attribute. How do I alter it? The docs say it is read-only. Is there even a way to alter the underlying storage class? I am working with a migrated database and can't get the urls of the old directory structure to apply the new deployment. The MEDIA_ROOT is set fine, upload_to is being used in models, so new objects get saved correctly, but old ones are expected to be in the MEDIA_ROOT by the application, which is not the case.
Solution 1:[1]
From your model get all instance and change the name attribute. For example in your model you ave a Many-to-many relationships to a document.
class Document(models.Model):
doc_file = models.FileField(upload_to=upload_path, max_length=500)
class Repository(models.Model):
documents = models.ManyToManyField(Document)
...
for doc in Repository.documents.all():
doc.doc_file.name = new_full_path
doc.save()
Another way is use Query Expressions
Repository.document.all().update(
documents =Func(
F('documents'),
Value(old_path), Value(new_path),
function='replace'
)
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cristian Festi |
