区分Django M2M信号中更新和创建的动作

问题描述 投票:0回答:1

我希望执行以下操作。创建新项目时,我想通知分配给该项目的每个人都有一个新项目可用。

这是我的简化项目模型:

class SalesProject(models.Model):
    sales_project_name = models.CharField(max_length=100)
    userProfile = models.ManyToManyField('UserProfile', blank=True)
    history = HistoricalRecords(excluded_fields=['version', 'project_status'])

    def __str__(self):
        return self.sales_project_name

创建项目时,我将发出以下信号:

def CreateProjectNotification(sender, **kwargs):
    if kwargs['action'] == "post_add" and kwargs["model"] == UserProfile:

        for person in kwargs['instance'].userProfile.all():

            #some check here to prevent me from creating a notification for the creator or the project
            Notifications.objects.create(
                target= person.user,
                extra = 'Sales Project',
                object_url = '/project/detail/' + str(kwargs['instance'].pk) + '/',
                title = 'New Sales Project created')

我之所以使用m2m_changed.connect而不是post_save的原因是,我希望访问M2M字段UserProfile来发送通知。由于在创建时不会将对象添加到穿透表,因此我不能使用post_save,而是必须跟踪穿透表中的更改。

问题话虽如此,只要调用save()函数并且更改的模型为UserProfile模型,该信号就会运行。

例如,这是有问题的,添加新用户后,我不希望发送相同的消息。相反,我希望运行一个单独的信号来处理。

除了使用if else区分对象的创建和添加相关的M2M对象之外,还有其他方法吗?

我希望执行以下操作。创建新项目时,我想通知分配给该项目的每个人都有一个新项目可用。这是我的简化项目模型:...

python django django-signals
1个回答
0
投票

您应尽可能避免使用信号,因为它们是explained here的不良做法。

© www.soinside.com 2019 - 2024. All rights reserved.