Django: how to execute code ONLY after the first t

2019-09-09 04:16发布

I'm trying to get create_reminder_send_message() executed THE FIRST TIME the Reminder object is saved AND the Reminder.users is saved. The code as it is executes every time I update the object... what am I missing? How can I accomplish what I want?

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)

1条回答
Deceive 欺骗
2楼-- · 2019-09-09 05:10

Django's m2m_changed signal offers you an action argument. You could check in your signal receiver if the action is pre_add and then check if already a reminder exists. This will work except for the case when all reminders get deleted and a new one gets created - don't know if it's ok for you to execute the code then. Otherwise the only possibility is storing additional data, eg. you could set a boolean to True at the first time or store the instance as well in your Message object, so you can check if a message already exists...

查看更多
登录 后发表回答