我有一个模型,我的目标是生成主键(字符串),然后重命名上传的文件以匹配该字符串。这是我缩短的模型和我使用的upload_to
函数。
class Thing(models.Model):
id = models.CharField(primary_key=True, max_length=16)
photo = ImageField('Photo', upload_to=upload_path, null=False, blank=False)
...
def upload_path(instance, filename):
if not instance.id:
randid = random_id(16) # This returns a 16 character string of ASCII characters
while Thing.objects.filter(id=randid).exists():
logger.error("[Thing] ThingID of %s already exists" % randid)
randid = random_id(16)
instance.id = randid
return "%s%s" % ("fullpath/",randid)
这会导致图像在适当的路径中正确地重命名为随机字符串。但是,主键设置为空字符串。
如何使用生成的主键重命名ImageField文件和正确保存生成的主键?
答案 0 :(得分:0)
您可以在Model上定义save方法。设置True null 和空白 ImageField,如果必须控制空字段,则可以在模型表单上控制它们。因此,您可以轻松地在DB上为模型生成唯一ID。然后,您可以使用唯一ID或自定义生成ID保存图像。最好使用我建议的主键的默认唯一整数id。
class Thing(models.Model):
fake_id = models.CharField(max_length=16)
photo = ImageField('Photo', upload_to=upload_path, null=True, blank=True)
def save(self, *args, **kwargs):
imagefile = self.photo
self.photo = ''
super(Thing, self).save(*args, **kwargs)
""" after superclass save, you can use self.id also its unique integer """
randid = random_id(16) # This returns a 16 character string of ASCII characters
while Thing.objects.filter(id=randid).exists():
logger.error("[Thing] ThingID of %s already exists" % randid)
randid = random_id(16)
self.fake_id = randid
"""manipulate rename and upload your file here you object is 'imagefile' """
save_dir = "fullpath/" + new_file_name_with_randid
self.photo = save_dir
super(Thing, self).save(*args, **kwargs)
答案 1 :(得分:0)
我最终删除了upload_to
回拨,并在Thing
的{{1}}方法中执行了此操作。
save()