models.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. from django.db import models
  2. from account.models import User
  3. # 引入内置信号
  4. from django.db.models.signals import post_save
  5. # 引入信号接收器的装饰器
  6. from django.dispatch import receiver
  7. class Group(models.Model):
  8. # 群id
  9. group_id = models.AutoField(primary_key=True)
  10. # 群名
  11. group_name = models.CharField(max_length=50, blank=False)
  12. # 群管理员
  13. creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="my_groups")
  14. # 群成员(多对多)
  15. members = models.ManyToManyField(User, related_name="joined_groups")
  16. def to_json(self):
  17. return {'group_id': self.group_id, 'group_name': self.group_name}
  18. def get_root_folder(self):
  19. return self.folders.get(father_folder=None)
  20. def __str__(self):
  21. return str(self.group_id)
  22. # 信号接收函数,每当新建Group实例的时候自动调用
  23. @receiver(post_save, sender=Group)
  24. def add_creator_to_group_members(sender, instance, created, **kwargs):
  25. if created and not instance.members.filter(username=instance.creator.username):
  26. instance.members.add(instance.creator)