Django-如何清除多次保存

时间:2019-04-05 15:04:23

标签: django django-models

我有以下模型。

class Post(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
    image = models.ImageField(max_length=255, upload_to='posts/images/', null=True, blank=True)
    thumbnail = models.FilePathField(path=settings.MEDIA_ROOT, max_length=255, null=True, blank=True)

如您所见,我这里需要两张图像,即用户上传的原始图像,以及将在主页上使用的缩略图版本。

问题是我正在使用以下代码在save方法上创建缩略图:

def save(self, *args, **kwargs):
    super(Post, self).save(*args, **kwargs)
    # Get the thumbnail from the image
    if self.image:
        self.thumbnail = get_thumbnail(self.image, '500x500', crop='center', quality=85).url
    super(Post, self).save(*args, **kwargs)

我无法删除第一个super(Post, self).save(*args, **kwargs),因为我希望self.image可用,而我不能删除第二个super(Post, self).save(*args, **kwargs),因为这样缩略图将不会不能保存。

我很确定必须有另一种方法。

能给我一些指示吗?

1 个答案:

答案 0 :(得分:1)

使用QuerySet的update()方法

class Post(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
    image = models.ImageField(max_length=255, upload_to='posts/images/', null=True, blank=True)
    thumbnail = models.FilePathField(path=settings.MEDIA_ROOT, max_length=255, null=True, blank=True)

    def save(self, *args, **kwargs):
        super(Post, self).save(*args, **kwargs)
        # Get the thumbnail from the image
        if self.image:
            thumbnail = get_thumbnail(self.image, '500x500', crop='center', quality=85).url
            Post.objects.filter(pk=self.pk).update(thumbnail=thumbnail)

注意:更新过程应在 if... 子句中:)