删除模型时,如何删除内联数据和上传的文件

时间:2013-05-17 04:53:55

标签: django models inlines

models.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')

admin.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)

删除问题模型后,如何删除预览和上传的文件?有人可以帮帮我吗?

1 个答案:

答案 0 :(得分: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/