Python Django 调用post_delete() 做自定义删除

最近做一个项目, 因为上传的文件没有采用django自带的FileField来保存, 导致删除对象时, 需要在views中添加代码来删除其关联的文件. 研究了一下, 发现django中可以通过post_delete来自定义删除行为. 示例代码如下:

$ mkdir mysite
$ cd mysite/
$ virtualenv --python=python3.6 venv
$ source venv/bin/activate
$ pip install django
$ python -m django startproject mysite .
$ python manage.py startapp blog
$ vim blog/models.py 
$ cat blog/models.py
from django.conf import settings
from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.contrib.auth.models import User


class Article(models.Model):
    title = models.CharField(max_length=80)
    text = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    attach = models.CharField(max_length=255)    # 文件上传后保存在服务器上的路径


@receiver(post_delete, sender=Article)
def delete_upload_files(sender, instance, **kwargs):
        files = getattr(instance, 'attach', '')
        if not files:
            return 
        fname = os.path.join(settings.MEDIA_ROOT, files)
        if os.path.isfile(fname):
            os.remove(fname)
$ echo "MEDIA_URL = '/media/'" >> mysite/settings.py 
$ echo "MEDIA_ROOT = os.path.join(BASE_DIR, 'media')" >> mysite/settings.py

大致就这些了

你可能感兴趣的:(Python Django 调用post_delete() 做自定义删除)