0

模型.py

    class Issue(models.Model):
        issueId = models.AutoField(primary_key=True)
        title = models.CharField(max_length = 20)
        year = models.IntegerField()
        issueDate = models.DateField()

    class Preview(models.Model):
        issueId = models.ForeignKey(Issue);
        previewPath = models.FileField(upload_to='./upload/magazine_sample')

管理员.py

    class PreviewInline(object):
        model = Preview
        extra = 1
        style = 'accordion'
        max_num = 1

    class IssueAdmin(object):
        list_display = ('title',)
        inlines = [PreviewInline]

    admin.site.register(Issue, IssueAdmin)

删除问题模型时如何删除预览和上传的文件?任何人都可以帮助我吗?

4

1 回答 1

1

您确定该问题没有被删除吗?ForeignKey 的默认行为是级联删除:

ForeignKey.on_delete 当一个被 ForeignKey 引用的对象被删除时,Django 默认会模拟 SQL 约束 ON DELETE CASCADE 的行为,同时也会删除包含 ForeignKey 的对象。可以通过指定 on_delete 参数来覆盖此行为。

你用的是sqlite3吗?我不确定它是否默认启用了级联。

要删除图像,您可能需要使用以下pre_delete信号:

from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import Preview

@receiver(pre_delete, sender=Preview)
def delete_image(sender, instance, using):
    # delete the image -> instance.previewPath

有关信号的更多信息: https ://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.pre_delete https://docs.djangoproject.com/en/dev/topics/signals /

于 2013-05-17T13:06:44.923 回答