Django: how to execute code ONLY after the first time a M2M relationship is added?

一个人想着一个人 提交于 2019-12-11 19:00: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:


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...



来源:https://stackoverflow.com/questions/17368707/django-how-to-execute-code-only-after-the-first-time-a-m2m-relationship-is-adde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!