首頁 > 後端開發 > Python教學 > 重寫 django 模型中的刪除方法

重寫 django 模型中的刪除方法

WBOY
發布: 2024-02-11 19:15:04
轉載
1410 人瀏覽過

重写 django 模型中的删除方法

問題內容

我有一個頁面模型,在儲存物件期間呼叫 save 方法中的列印。但是,當物件被刪除時,不會觸發任何列印,並且似乎永遠不會呼叫刪除方法。那我應該如何覆蓋預設的刪除方法呢?

class Page(models.Model):
    image = models.ImageField()
    number = models.PositiveIntegerField(default=0, blank=True, null=True)
    chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE)

    def get_upload_path(self, filename):
        work_slug = self.chapter.volume.work.slug
        translator_name = slugify(self.chapter.volume.translator)
        volume_number = self.chapter.volume.number
        chapter_number = self.chapter.number
        name, extension = filename.rsplit('.', 1)
        return f'media/{work_slug}/{translator_name}/volumes/volume-{volume_number}/chapters/chapter-{chapter_number}/page-{self.number}.{extension}'

    def save(self, *args, **kwargs):
        if not self.pk:
            last_page = self.chapter.page_set.last()
            if last_page:
                self.number = last_page.number + 1
        self.image.name = self.get_upload_path(self.image.name)
        self.image.storage = s3
        print(f"Saving Page with image: {self.image.name}")
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        print(f"Deleting Page with image: {self.image.name}")

        image_name = self.image.name
        try:
            s3.delete(image_name)
            print(f"Successfully deleted from S3: {image_name}")
        except Exception as e:
            print(f"Error deleting from S3: {e}")

        super().delete(*args, **kwargs)
登入後複製


正確答案


刪除一個物件時呼叫 model 的 delete 方法。如果您嘗試刪除查詢集(例如從 django 管理清單頁面刪除),您必須覆寫模型的查詢集。

class PageQuerySet(models.QuerySet):
    def delete(self):
        print("deleting queryset")
        return super().delete()


class PageManager(models.Manager):
    def get_queryset(self):
        return PageQuerySet(model=self.model, using=self._db, hints=self._hints)


class Page(models.Model):
    image = models.ImageField()
    number = models.PositiveIntegerField(default=0, blank=True, null=True)
    chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE)

    objects = PageManager()

    def get_upload_path(self, filename):
        work_slug = self.chapter.volume.work.slug
        translator_name = slugify(self.chapter.volume.translator)
        volume_number = self.chapter.volume.number
        chapter_number = self.chapter.number
        name, extension = filename.rsplit('.', 1)
        return f'media/{work_slug}/{translator_name}/volumes/volume-{volume_number}/chapters/chapter-{chapter_number}/page-{self.number}.{extension}'

    def save(self, *args, **kwargs):
        if not self.pk:
            last_page = self.chapter.page_set.last()
            if last_page:
                self.number = last_page.number + 1
        self.image.name = self.get_upload_path(self.image.name)
        self.image.storage = s3
        print(f"Saving Page with image: {self.image.name}")
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        print(f"Deleting Page with image: {self.image.name}")

        image_name = self.image.name
        try:
            s3.delete(image_name)
            print(f"Successfully deleted from S3: {image_name}")
        except Exception as e:
            print(f"Error deleting from S3: {e}")

        super().delete(*args, **kwargs)
登入後複製

以上是重寫 django 模型中的刪除方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板