我正在应用post_save信号来为每个对象应用用户权限,然后相应地过滤查询集。我的模型是这样的:class Project(models.Model): # Relations with other entities. employees = models.ManyToManyField('staff.Person', through='project.PersonProjectMembership', related_name='projects') research_groups = models.ManyToManyField('group.Group', related_name='projects', through='project.ProjectGroupMembership') departments = models.ManyToManyField('department.Department', related_name='projects', through='project.ProjectDepartmentMembership')问题是:当我收到保存后的信号时,尽管我已经输入了部门,research_groups和员工的值,但它们似乎总是空着的。有什么我想念的吗?更新:在当前代码下方,该代码尚未按预期运行。我已将post_save更改为m2m_changed。from django.db.models.signals import m2m_changedfrom django.db import modelsfrom django.dispatch.dispatcher import receiverclass Project(models.Model): employees = models.ManyToManyField('staff.Person', through='project.PersonProjectMembership', related_name='projects')class PersonProjectMembership(models.Model): project = models.ForeignKey('project.Project', related_name="person_memberships") person = models.ForeignKey('staff.Person', related_name="project_memberships") lead = models.BooleanField(default=False) position = models.CharField(max_length=50) project_manager = models.BooleanField( default=False ) class Meta: permissions = ( ('view_personprojectmembership', _('View person project membership')), )@receiver(m2m_changed, sender=Project.employees.through)def _on_save_project_assign_privileges(sender, instance, action, reverse, model, pk_set, using, **kwargs): # [...]
3 回答
哈士奇WWW
TA贡献1799条经验 获得超6个赞
您可能知道,Many2Many关系是通过附加表存储的,该表包含关系两端的主键。因此,与Many2Many关系的保存模型实例是两个步骤的过程:
首先,实例被保存:数据库中的新记录被创建并且实例接收它的主键。
post_save
此时被解雇。之后,关系被保存:在关系表中创建记录。
m2m-changed
此时会触发信号。
换句话说,当post_save
被解雇时,尚未处理m2m关系。
胡说叔叔
TA贡献1804条经验 获得超8个赞
在深入研究代码并进行简单测试之后,我尝试了krasnoperov建议的m2m_changed信号。我意识到,如果您明确声明一个“直通”模型(在本例中为“ PersonProjectMembership”),则此信号将无法正常工作。
然后我再次考虑,并将我的方法链接到“ PersonProjectMembership”的post_save信号。那很好。
添加回答
举报
0/150
提交
取消