Django:如何仅在首次添加M2M关系后才执行代码? [英] Django: how to execute code ONLY after the first time a M2M relationship is added?
问题描述
我试图让create_reminder_send_message()在第一次执行时保存Reminder对象,并保存Reminder.users.每次更新对象时都会执行原样的代码……我缺少什么?我该如何完成我想要的?
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)
推荐答案
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...
这篇关于Django:如何仅在首次添加M2M关系后才执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!