models.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from django.db import models
  2. # 文件夹表
  3. from account.models import User
  4. from group.models import Group
  5. # 引入内置信号
  6. from django.db.models.signals import post_save
  7. # 引入信号接收器的装饰器
  8. from django.dispatch import receiver
  9. class Folder(models.Model):
  10. # 文件夹id
  11. folder_id = models.AutoField(primary_key=True)
  12. # 文件夹名
  13. folder_name = models.CharField(max_length=50, blank=False, default='root')
  14. # 父节点
  15. father_folder = models.ForeignKey('self', blank=True, on_delete=models.CASCADE, null=True,
  16. related_name='children_folders')
  17. # 所有者
  18. owner = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='folders')
  19. group = models.ForeignKey(Group, on_delete=models.DO_NOTHING, related_name='folders', null=True)
  20. def to_json(self):
  21. return {'folder_id': self.folder_id, 'folder_name': self.folder_name, 'father_folder_id': self.father_folder_id}
  22. def check_permission(self, user:User):
  23. return self.owner == user or user.joined_groups.filter(group_id=self.group_id)
  24. def __str__(self):
  25. return str(self.folder_id)
  26. # 信号接收函数,每当新建User实例的时候自动调用
  27. @receiver(post_save, sender=User)
  28. def create_user_root_folder(sender, instance, created, **kwargs):
  29. if created:
  30. root_folder = Folder.objects.create(owner=instance)
  31. # 信号接收函数,每当新建Group实例的时候自动调用
  32. @receiver(post_save, sender=Group)
  33. def create_group_root_folder(sender, instance, created, **kwargs):
  34. if created:
  35. root_folder = Folder.objects.create(owner=instance.creator, group=instance)