Home > Backend Development > Python Tutorial > Override delete method in django model

Override delete method in django model

WBOY
Release: 2024-02-11 19:15:04
forward
1363 people have browsed it

重写 django 模型中的删除方法

Question content

I have a page model that calls print in the save method during saving of the object. However, when the object is deleted, no printing is triggered and the delete method never seems to be called. So how should I override the default delete method?

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)
Copy after login


Correct answer


Call the delete method of model when deleting an object. If you try to delete a queryset (e.g. from the django admin list page), you must overwrite the model's queryset.

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)
Copy after login

The above is the detailed content of Override delete method in django model. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template