import uuid from django.db import models from folder.models import Folder from account.models import User from group.models import Group from django.conf import settings # 引入内置信号 from django.db.models.signals import post_delete # 引入信号接收器的装饰器 from django.dispatch import receiver import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 文件表 class File(models.Model): # 文件id file_id = models.UUIDField(primary_key=True, default=uuid.uuid4, auto_created=True, editable=False) # 文件名 file_name = models.CharField(max_length=50, blank=False) # 从属的文件夹 father_folder = models.ForeignKey(Folder, on_delete=models.CASCADE, related_name='children_files') # 更新时间 update_time = models.DateTimeField(auto_now=True, editable=False) # 文件类型 file_type = models.CharField(max_length=32) # 文件大小 # file_size = models.CharField(max_length=16) key = models.CharField(max_length=1024, null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='files') group = models.ForeignKey(Group, on_delete=models.DO_NOTHING, related_name='files', null=True) def get_path(self): return settings.MEDIA_ROOT / f'{self.file_name}_{self.file_id}' def to_json(self): return {'file_id': self.file_id, 'file_name': self.file_name, 'father_folder_id': self.father_folder_id, 'update_time': self.update_time, 'file_type': self.file_type, # 'file_size': self.file_size, 'key': self.key, 'file': 'file'} # 信号接收函数,每当删除file时自动删除文件 @receiver(post_delete, sender=File) def delete_file(sender, instance, **kwargs): try: os.remove(instance.get_path()) except: print('找不到文件')