0

我有一个模型,我的目标是生成主键(字符串),然后重命名上传的文件以匹配该字符串。这是我的缩短模型和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 文件正确保存生成的主键?

4

2 回答 2

0

您可以通过在模型上定义保存方法来实现此低谷。设置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)
于 2012-09-27T06:21:07.900 回答
0

我最终删除了回调并在's方法中完成upload_to了这一切。Thingsave()

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 save(self, *args, **kwargs):
        randid = random_id(16)
        while Thing.objects.filter(id=randid).exists():
            logger.error("[Thing] ThingID of %s already exists" % randid)
            randid = random_id(16)
        self.id = randid
        self.photo.name = ".".join([randid, self.photo.name.split(".")[-1]])   # This adds the file extension to the random id generated
        super(Thing,self).save(*args, **kwargs)
于 2012-09-28T14:35:02.157 回答