gpt4 book ai didi

python - post_save 信号和关系

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:54 26 4
gpt4 key购买 nike

我正在应用 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')

问题是:当我收到保存后信号时,虽然我已经输入了部门、研究组和员工的值,但它们似乎总是空的。有什么我错过的吗?

更新:在当前代码下方,尚未按预期工作。我已经通过 m2m_changed 更改了 post_save。

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')

我保存项目的时间线如下:

  1. 项目.保存()
  2. PersonProjectMembership.save()

所以很正常,在 Project.post_save employees 上仍然是空的。我必须做的是听取 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.throughhttps://docs.djangoproject.com/en/1.9/topics/signals/

最佳答案

在深入研究我的代码并进行简单测试后,我按照 krasnoperov 的建议尝试了 m2m_changed 信号。我意识到,如果您明确声明一个“直通”模型(在我的例子中为“PersonProjectMembership”),则此信号无法正常工作。

然后我又想了想,将我的方法链接到“PersonProjectMembership”的post_save 信号。这非常有效。

关于python - post_save 信号和关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17149305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com