Rumah > pembangunan bahagian belakang > Tutorial Python > Gantikan kaedah padam dalam model django

Gantikan kaedah padam dalam model django

WBOY
Lepaskan: 2024-02-11 19:15:04
ke hadapan
1410 orang telah melayarinya

重写 django 模型中的删除方法

Kandungan soalan

Saya mempunyai model halaman yang memanggil cetakan dalam kaedah simpan semasa menyimpan objek. Walau bagaimanapun, apabila objek dipadamkan, tiada pencetakan dicetuskan dan kaedah padam nampaknya tidak pernah dipanggil. Jadi bagaimana saya harus mengatasi kaedah padam lalai?

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)
Salin selepas log masuk


Jawapan betul


Panggil kaedah delete model apabila memadam objek. Jika anda cuba memadam set pertanyaan (cth. daripada halaman senarai pentadbir django), anda mesti menulis ganti set pertanyaan model.

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)
Salin selepas log masuk

Atas ialah kandungan terperinci Gantikan kaedah padam dalam model django. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:stackoverflow.com
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan