models.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import uuid
  2. from django.db import models
  3. from folder.models import Folder
  4. from account.models import User
  5. from group.models import Group
  6. from django.conf import settings
  7. # 引入内置信号
  8. from django.db.models.signals import post_delete
  9. # 引入信号接收器的装饰器
  10. from django.dispatch import receiver
  11. import os
  12. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  13. # 文件表
  14. class File(models.Model):
  15. # 文件id
  16. file_id = models.UUIDField(primary_key=True, default=uuid.uuid4, auto_created=True, editable=False)
  17. # 文件名
  18. file_name = models.CharField(max_length=50, blank=False)
  19. # 从属的文件夹
  20. father_folder = models.ForeignKey(Folder, on_delete=models.CASCADE, related_name='children_files')
  21. # 更新时间
  22. update_time = models.DateTimeField(auto_now=True, editable=False)
  23. # 文件类型
  24. file_type = models.CharField(max_length=32)
  25. # 文件大小
  26. # file_size = models.CharField(max_length=16)
  27. key = models.CharField(max_length=1024, null=True, blank=True)
  28. owner = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='files')
  29. group = models.ForeignKey(Group, on_delete=models.DO_NOTHING, related_name='files', null=True)
  30. def get_path(self):
  31. return settings.MEDIA_ROOT / f'{self.file_name}_{self.file_id}'
  32. def to_json(self):
  33. return {'file_id': self.file_id,
  34. 'file_name': self.file_name,
  35. 'father_folder_id': self.father_folder_id,
  36. 'update_time': self.update_time,
  37. 'file_type': self.file_type,
  38. # 'file_size': self.file_size,
  39. 'key': self.key,
  40. 'file': 'file'}
  41. # 信号接收函数,每当删除file时自动删除文件
  42. @receiver(post_delete, sender=File)
  43. def delete_file(sender, instance, **kwargs):
  44. try:
  45. os.remove(instance.get_path())
  46. except:
  47. print('找不到文件')