I have a Django model Reminder related to Event model.
class Reminder(models.Mod开发者_如何学JAVAel):
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,)
How, using __init__
set Reminder's date field value to the date of Event model related to it - 7 days ? Is it possible ?
I don't know what exactly you need, but:
1) If you need Reminder.date always return 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) If you need to set the date on event save or on reminder save, do this:
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)
Please note that I haven't tested the code and there might be typos.
just add this to the ____init____ method of your Reminder class. If you are setting this in the ____init____ method then you need to create the Event at the same time.
e = Event() self.event = e self.date = e.date e.put()
精彩评论