from django.db import models # 文件夹表 from account.models import User from group.models import Group # 引入内置信号 from django.db.models.signals import post_save # 引入信号接收器的装饰器 from django.dispatch import receiver class Folder(models.Model): # 文件夹id folder_id = models.AutoField(primary_key=True) # 文件夹名 folder_name = models.CharField(max_length=50, blank=False, default='root') # 父节点 father_folder = models.ForeignKey('self', blank=True, on_delete=models.CASCADE, null=True, related_name='children_folders') # 所有者 owner = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='folders') group = models.ForeignKey(Group, on_delete=models.DO_NOTHING, related_name='folders', null=True) def to_json(self): return {'folder_id': self.folder_id, 'folder_name': self.folder_name, 'father_folder_id': self.father_folder_id} def check_permission(self, user:User): return self.owner == user or user.joined_groups.filter(group_id=self.group_id) def __str__(self): return str(self.folder_id) # 信号接收函数,每当新建User实例的时候自动调用 @receiver(post_save, sender=User) def create_user_root_folder(sender, instance, created, **kwargs): if created: root_folder = Folder.objects.create(owner=instance) # 信号接收函数,每当新建Group实例的时候自动调用 @receiver(post_save, sender=Group) def create_group_root_folder(sender, instance, created, **kwargs): if created: root_folder = Folder.objects.create(owner=instance.creator, group=instance)