models.py
class Entry(models.Model):
owner = models.ForeignKey(User, related_name='owner')
myfile = models.FileField(upload_to='my_files/%Y/%m/%d')
我需要使用此模型更改以前上传的文件的扩展名。
答案 0 :(得分:1)
请注意upload_to
可以调用,如下所示:
import date
import os
def upload_path(instance, filename):
d = date.today()
parts = os.path.splitext(filename)
return 'my_files/%s/%s/%s/%s.%s' % (
d.year, d.month, d.day, parts[0], 'new_ext')
所以,在你的模型中:
class Entry(models.Model):
# ...
myfile = models.FileField(upload_to=upload_path)
这对您处理过去已上传的文件没有帮助,但新上传的文件名正确无误。
答案 1 :(得分:0)
您需要以这种方式重新定义模型的保存方法:
import os
def save(self, *args, **kwargs):
if self.pk:
prev_instance = Entry.objects.get(pk=self.pk)
if prev_instance.myfile:
name = os.path.splitext(prev_instance.myfile)[0]
os.rename(prev_instance.myfile, name + ".old")
super(Entry, self).save(*args, **kwargs)