我有一个与事件模型相关的Django模型提醒。
class Reminder(models.Model):
email = models.EmailField("e-mail")
event = models.ForeignKey(Event, unique=True, related_name='event',)
date = models.DateTimeField(_(u"Remind date"), auto_now_add=False,)
class Event(models.Model):
date = models.DateTimeField(_(u"Event Date"), auto_now_add=True,)
如何使用__init__
将Reminder的日期字段值设置为与其相关的事件模型的日期 - 7天?有可能吗?
答案 0 :(得分:2)
我不知道你到底需要什么,但是:
1)如果你需要Reminder.date,总是返回Event.date - 7
import datetime
class Reminder(models.Model):
email = models.EmailField("e-mail")
event = models.ForeignKey(Event, unique=True, related_name='event',)
def date(self):
return self.event.date - datetime.timedelta(days=7)
class Event(models.Model):
date = models.DateTimeField(_(u"Event Date"), auto_now_add=True,)
2)如果您需要在事件保存或提醒保存时设置日期,请执行以下操作:
import datetime
class Reminder(models.Model):
email = models.EmailField("e-mail")
event = models.ForeignKey(Event, unique=True, related_name='event',)
date = models.DateTimeField(_(u"Remind date"), auto_now_add=False,)
# update date on save
def save(self, *args, **kwargs):
self.date = self.event.date - datetime.timedelta(days=7)
super(Reminder, self).save(*args, **kwargs)
class Event(models.Model):
date = models.DateTimeField(_(u"Event Date"), auto_now_add=True,)
# update all reminders on event save
def save(self, *args, **kwargs):
reminder_date = self.date - datetime.timedelta(days=7)
self.reminders.update(date=reminder_date)
super(Event, self).save(*args, **kwargs)
请注意,我没有测试过代码,可能存在拼写错误。
答案 1 :(得分:1)
只需将此添加到提醒类的____init____方法即可。如果你在____init____方法中设置它,那么你需要同时创建事件。
e = Event() self.event = e self.date = e.date e.put()