0

我试图让 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)
4

1 回答 1

0

Django 的m2m_changed信号为您提供了一个action参数action如果是,您可以检查您的信号接收器pre_add,然后检查是否已经存在提醒。除了删除所有提醒并创建新提醒的情况外,这将起作用 - 不知道您是否可以执行代码。否则,唯一的可能性是存储额外的数据,例如。您可以True在第一次设置一个布尔值或将其存储instance在您的Message对象中,这样您就可以检查消息是否已经存在......

于 2013-06-28T20:03:58.417 回答