1234567891011121314151617181920212223242526272829303132333435 |
- from django.db import models
- from account.models import User
- # 引入内置信号
- from django.db.models.signals import post_save
- # 引入信号接收器的装饰器
- from django.dispatch import receiver
- class Group(models.Model):
- # 群id
- group_id = models.AutoField(primary_key=True)
- # 群名
- group_name = models.CharField(max_length=50, blank=False)
- # 群管理员
- creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="my_groups")
- # 群成员(多对多)
- members = models.ManyToManyField(User, related_name="joined_groups")
- def to_json(self):
- return {'group_id': self.group_id, 'group_name': self.group_name}
- def get_root_folder(self):
- return self.folders.get(father_folder=None)
- def __str__(self):
- return str(self.group_id)
- # 信号接收函数,每当新建Group实例的时候自动调用
- @receiver(post_save, sender=Group)
- def add_creator_to_group_members(sender, instance, created, **kwargs):
- if created and not instance.members.filter(username=instance.creator.username):
- instance.members.add(instance.creator)
|