我有两个模型团队和项目,两个模型都有彼此有很多关系的领域。我希望能够自动更新第二个模型说,当我更新团队在项目模型领域的团队。
项目模型
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()
1条答案
按热度按时间gtlvzcf81#
根本不需要信号。你使用**
ManyToManyField
**[Django-doc]的方式不对。这种关系就像Django中的任何关系一样,是双向的。因此,您不需要以两种方式指定它,如果您在
Project
中指定一个,例如Team
s,则可以访问Team
的Project
s。的确:因此,这意味着如果将
Team
添加到Project
,则:那么
my_team
将自动将my_project
作为项目: