views:

47

answers:

2

I have a Django model Reminder related to Event model.

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,)

How, using __init__ set Reminder's date field value to the date of Event model related to it - 7 days ? Is it possible ?

+1  A: 

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()
Conceited Code
not something like self.date = self.event.date ?
crivateos
Sorry. I misunderstood your question. I edited my answer.
Conceited Code
+1  A: 

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.

Dmitry Gladkov