Django - 将所有相关的ForeignKeys删除到模型中

时间:2017-11-09 16:42:55

标签: django

我有一个名为Team的模型,与Agent(我的用户模型)有一个ForeignKey关系。当team_leader的代理停用该团队时,设置为当前团队的team_member的所有代理都将删除其team_member属性并设置为NULL /空。

我读过thisthis,我知道我应该对._meta.get_fields()Collector类做点什么。我正在尝试使用get_fields()但我们没有设法让它发挥作用。

models.py

class Agent(AbstractUser):
    team_member = models.ForeignKey('AgentTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='team_member')
    team_leader = models.OneToOneField('AgentTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='team_leader')

class AgentTeam(models.Model):
    team_is_active = models.BooleanField(default=False)

views.py

def deactivate_team(request):
    request.user.AgentTeam.team_is_active = False  # request.user in this case is the team_leader

    # I need to set all the Agent's with team_member set to the request.user's team to NULL.  I have experimented with the code below and gotten only errors, mostly related to ReverseToOne like ''ReverseManyToOneDescriptor' object is not iterable'
    agents = [
        f for f in AgentTeam._meta.get_fields()
        if (f.one_to_many)
        and f.auto_created and not f.concrete
    ]
    for agent in agents:
        objects = getattr(AgentTeam, agent.name).all()
        for object in objects:
            object.team_member = None

请提供一些关于我的观看代码和我所犯错误的评论和指示。谢谢。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,我没有看到你需要遍历模型字段的原因。

您可以在不必担心模型的任何字段的情况下离开。您可以在AgentTeam值无效时更新所有代理的team_member状态。这可以在视图中或在模型save()方法中完成。例如:

class Agent(AbstractUser):
    team_member = models.ForeignKey('AgentTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='team_member')
    team_leader = models.OneToOneField('AgentTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='team_leader')

class AgentTeam(models.Model):
    team_is_active = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        super(AgentTeam, self).save(*args, **kwargs)
        if not self.team_is_active:
            Agent.objects.filter(
                team_member=self
            ).update(team_member=None)

然后在视图中:

def deactivate_team(request):
    team = request.user.AgentTeam
    team.team_is_active = False
    team.save()