如何在django 4.2中使用m2m_changed信号更新模型信息

wztqucjr  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(115)

我有两个模型团队和项目,两个模型都有彼此有很多关系的领域。我希望能够自动更新第二个模型说,当我更新团队在项目模型领域的团队。
项目模型

from django.db import models
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from .team import Team
class Project(models.Model):
    PENDING = 'Pending'
    IN_PROGRESS = 'In Progress'
    COMPLETED = 'Completed'

    STATUS_CHOICES = [
        (PENDING, 'Pending'),
        (IN_PROGRESS, 'In Progress'),
        (COMPLETED, 'Completed'),
    ]

    name = models.CharField(max_length=70)
    description = models.TextField()
    start_date = models.DateField()
    end_date = models.DateField()
    teams = models.ManyToManyField('Team', blank=True, related_name='team_projects')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=PENDING)

    def __str__(self) -> str:
        return str(self.name)

团队模型

from django.db import models
from django.contrib.auth import get_user_model

# from . import Project

class Team(models.Model):
    name = models.CharField(max_length=70)
    description = models.TextField()
    members = models.ManyToManyField(get_user_model(), blank=True)
    projects = models.ManyToManyField('Project', blank=True, related_name='teams_projects')

    def __str__(self) -> str:
        return str(self.name)

我试图研究这个信号,但我走进了死胡同。这就是我所尝试的。

@receiver(m2m_changed, sender=Project.teams.through)
def update_team_information(sender, instance, action, **kwargs):
    if action in ["post_add", "post_remove", "post_clear"]:
        for team_id in instance.teams.all().values_list('id', flat=True):
            team = Team.objects.get(pk=team_id)
            team.update_information()
gtlvzcf8

gtlvzcf81#

根本不需要信号。你使用**ManyToManyField**[Django-doc]的方式不对。这种关系就像Django中的任何关系一样,是双向的。
因此,您不需要以两种方式指定它,如果您在Project中指定一个,例如Team s,则可以访问TeamProject s。的确:

class Project(models.Model):
    # …
    teams = models.ManyToManyField('Team', blank=True, related_name='projects')

# …

class Team(models.Model):
    # …
    # no projects
    pass

因此,这意味着如果将Team添加到Project,则:

my_project.teams.add(my_team)

那么my_team将自动将my_project作为项目:

my_team.projects.all()  # contains my_project

相关问题