1

我有一个带有此模型的 Annonce 页面:

class AnnoncePage(Page):
    date = models.DateField("Date de publication", blank=True, null=True)
    description = RichTextField(features=['h2', 'h3', 'bold', 'italic', 'link', 'hr', 'ol', 'ul'], blank=True)
    lieu = models.CharField(blank=True, max_length=200)
    surface = models.PositiveSmallIntegerField(blank=True, null=True)
    nb_pieces = models.PositiveSmallIntegerField(blank=True, null=True)
    prix_affiché_index = models.CharField(blank=True, max_length=200, null=True)
    conditions_vente_et_prix = RichTextField(blank=True, features=['h2', 'h3', 'bold', 'italic', 'link', 'hr', 'ol', 'ul'])

    def main_image(self):
        gallery_item = self.gallery_images.first()
        if gallery_item:
            return gallery_item.image
        else:
            return None

    content_panels = Page.content_panels + [
        FieldPanel('date'),
        InlinePanel('gallery_images', label="Gallery images"),
        FieldPanel('lieu', classname="full"),
        FieldPanel('surface', classname="full"),
        FieldPanel('nb_pieces', classname="full"),
        FieldPanel('description', classname="full"),
        FieldPanel('prix_affiché_index', classname="full"),
        FieldPanel('conditions_vente_et_prix', classname="full")
    ]

    promote_panels = []
    settings_panels = []

    max_count = 20

class AnnoncePageGalleryImage(Orderable):
    page = ParentalKey(AnnoncePage, on_delete=models.SET_NULL, related_name='gallery_images', null=True)
    image = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True
    )

    panels = [
        ImageChooserPanel('image')
    ]

如何在删除 Annonce 页面本身后自动删除 Annonce 页面的图像?我需要更改模型吗?

4

1 回答 1

0

Wagtail 图像对象可以在其他地方使用。自动删除这些内容可能会对其他内容产生令人讨厌的副作用。

您可以添加delete方法AnnoncePage或使用pre_delete信号。您需要遍历所有相关的画廊图像并删除相关的 Wagtail 图像。Django 将文件保留在磁盘上,因此您可能也想处理它。

class AnnoncePage(Page):
    ...
    def delete(self):
         for gallery_image in self.gallery_images.all():
              # Delete the file on disk here ...
              # After, delete the db obj.
              gallery_image.image.all().delete()
         self.gallery_images.all().delete()
         super().delete()

免责声明:未经测试的代码。

https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods https://docs.djangoproject.com/en/dev/ref/signals/#pre-delete https: //docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.fields.files.FieldFile.delete

请注意,批量操作不会调用delete方法和信号。pre_delete您的里程可能会有所不同。

于 2020-10-13T09:28:35.510 回答