我正在应用 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')
问题是:当我收到保存后信号时,虽然我输入了部门、研究组和员工的值,但它们似乎总是空的。有什么我错过的吗?
更新:在当前代码下方,尚未按预期工作。我已将 post_save 更改为 m2m_changed。
from django.db.models.signals import m2m_changed
from django.db import models
from django.dispatch.dispatcher import receiver
class 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):
# [...]
解决方案
在我的项目模型中,我明确将 PersonProjectMembership 定义为 m2m 关系员工中的中间模型:
class Project(models.Model):
# Relations with other entities.
employees = models.ManyToManyField('staff.Person', through='project.PersonProjectMembership', related_name='projects')
我保存项目时的时间线如下:
- 项目.save()
- PersonProjectMembership.save()
因此,在 Project.post_save 上,员工仍然为空是正常的。我必须做的是听 PersonProjectMembership post_save 信号:
@receiver(post_save, sender=PersonProjectMembership)
def my_listener(**kwargs):
# do stuff [...]
查看https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ManyToManyField.through和https://docs.djangoproject.com/en/1.9/topics/signals /