我试图让 create_reminder_send_message() 在第一次保存 Reminder 对象并保存 Reminder.users 时执行。每次我更新对象时都会执行代码......我错过了什么?我怎样才能完成我想要的?
class Reminder(models.Model):
METHODS = (
('EM', 'Send Email'),
('TS', 'Create Dashboard Task'),
('ET', 'Both (recommended)')
)
info = models.TextField()
method = models.CharField(max_length=3, choices=METHODS, db_index=True,
help_text='''How should I remind the user? (
remember that the backend will not be able to
send the emails if the users haven't set it up
in their profile options)''')
users = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='reminders')
due_date = models.DateField(blank=True, null=True, db_index=True)
remind_date = models.DateField(db_index=True)
sent = models.BooleanField(default=False, db_index=True)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True,
related_name='created_by')
def create_reminder_send_message(sender, **kwargs):
'''
A signal that creates a new "Message" when a reminder is assigned
to a user or group of users.
'''
instance = kwargs.get('instance')
text = "I have added a new reminder for you. \nActivation date: {0}".format(instance.remind_date)
message = Message.objects.create(user=instance.created_by,
subject='New reminder!', body=text, draft=False)
message.to = instance.users.all()
message.received = timezone.now()
message.save()
models.signals.m2m_changed.connect(create_reminder_send_message, sender=Reminder.users.through)