【发布时间】:2020-10-04 13:14:50
【问题描述】:
我希望做以下事情。创建新项目时,我想通知分配给该项目的每个人有一个新项目可用。
这是我的简化项目模型:
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 对象的添加之外,还有其他方法吗?
【问题讨论】:
-
如果我理解正确,您想在创建新的
SalesProject时创建Notification? -
是的!但问题是我希望通过 M2M 字段访问用户配置文件模型,这就是为什么我必须使用 m2m 更改方法
-
我想做的第二件事是区分“更新”和“创建”,这是因为通过使用 m2m_change ,只要通过表发生更改,该函数就会运行,因此我无法区分该操作是“更新”还是“创建”
标签: python django django-signals