Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling recurring events in a Django calendar app

I'm developing a calendaring application in Django.

The relevant model structure is as follows:

class Lesson(models.Model):
  RECURRENCE_CHOICES = (
    (0, 'None'),
    (1, 'Daily'),
    (7, 'Weekly'),
    (14, 'Biweekly')
  )
  frequency = models.IntegerField(choices=RECURRENCE_CHOICES)
  lessonTime = models.TimeField('Lesson Time')
  startDate = models.DateField('Start Date')
  endDate = models.DateField('End Date')
  student = models.ForeignKey(Student)

class CancelledLesson(models.Model):
  lesson = models.ForeignKey(Lesson)
  student = models.ForeignKey(Student)
  cancelledLessonDate = models.DateField() # Actual date lesson has been cancelled, this is startDate + Frequency

class PaidLesson(models.Model):
  lesson = models.ForeignKey(Lesson)
  student = models.ForeignKey(Student)
  actualDate = models.DateField() # Actual date lesson took place
  paidAmt = models.DecimalField('Amount Paid', max_digits=5, decimal_places=2)
  paidDate = models.DateField('date paid')

class CompositeLesson(models.Model):
  # only used to aggregate lessons for individual lesson management
  lesson = models.ForeignKey(Lesson)
  student = models.ForeignKey(Student)
  actualDate = models.DateTimeField()
  isCancelled = models.BooleanField()
  canLesson = models.ForeignKey(CancelledLesson, blank=True, null=True)
  payLesson = models.ForeignKey(PaidLesson, blank=True, null=True)

Apparently this is all causing issues with displaying the lessons that belong to a particular student. What I am attempting to do is display a table that shows the Student name plus all instances of scheduled lessons. I am calculating the recurrence dynamically to avoid blowing up my database. Exceptions to the recurrences (i.e. lesson cancellations) are stored in their own tables. Recurrences are checked against the cancelled lesson table when the recurrences are generated.

See my code to generate recurrences (as well as a small catalog of what issues this is causing) here: Can't get key to display in Django template

I'm relatively inexperienced with Python, and am using this project as a way to get my head around a lot of the concepts, so if I'm missing something that's inherently "Pythonic", I apologize.

like image 896
Matthew Calabresi Avatar asked Jun 07 '12 18:06

Matthew Calabresi


2 Answers

The key part of your problem is that you're using a handful of models to track just one concept, so you're introducing a lot of duplication and complexity. Each of the additional models is a "type" of Lesson, so you should be using inheritance here. Additionally, most of the additional models are merely tracking a particular characteristic of a Lesson, and as a result should not actually be models themselves. This is how I would have set it up:

class Lesson(models.Model):
    RECURRENCE_CHOICES = (
        (0, 'None'),
        (1, 'Daily'),
        (7, 'Weekly'),
        (14, 'Biweekly')
    )

    student = models.ForeignKey(Student)
    frequency = models.IntegerField(choices=RECURRENCE_CHOICES)
    lessonTime = models.TimeField('Lesson Time')
    startDate = models.DateField('Start Date')
    endDate = models.DateField('End Date')
    cancelledDate = models.DateField('Cancelled Date', blank=True, null=True)
    paidAmt = models.DecimalField('Amount Paid', max_digits=5, decimal_places=2, blank=True, null=True)
    paidDate = models.DateField('Date Paid', blank=True, null=True)

class CancelledLessonManager(models.Manager):
    def get_query_set(self):
        return self.filter(cancelledDate__isnull=False)

class CancelledLesson(Lesson):
    class Meta:
        proxy = True

     objects = CancelledLessonManager()

class PaidLessonManager(models.Manager):
    def get_query_set(self):
        return self.filter(paidDate__isnull=False)

class PaidLesson(Lesson):
      class Meta:
          proxy = True

      objects = PaidLessonManager()

You'll notice that I moved all the attributes onto Lesson. This is the way it should be. For example, Lesson has a cancelledDate field. If that field is NULL then it's not cancelled. If it's an actual date, then it is cancelled. There's no need for another model.

However, I have left both CancelledLesson and PaidLesson for instructive purposes. These are now what's called in Django "proxy models". They don't get their own database table (so no nasty data duplication). They're purely for convenience. Each has a custom manager to return the appropriate matching Lessons, so you can do CancelledLesson.objects.all() and get only those Lessons that are cancelled, for example. You can also use proxy models to create unique views in the admin. If you wanted to have an administration area only for CancelledLessons you can, while all the data still goes into the one table for Lesson.

CompositeLesson is gone, and good riddance. This was a product of trying to compose these three other models into one cohesive thing. That's no longer necessary, and your queries will be dramatically easier as a result.

EDIT

I neglected to mention that you can and should add utility methods to the Lesson model. For example, while tracking cancelled/not by whether the field is NULL or not makes sense from a database perspective, from programming perspective it's not as intuitive as it could be. As a result, you might want to do things like:

@property
def is_cancelled(self):
    return self.cancelledDate is not None

...

if lesson.is_cancelled:
   print 'This lesson is cancelled'

Or:

import datetime

...

def cancel(self, date=None, commit=True):
    self.cancelledDate = date or datetime.date.today()
    if commit:
        self.save()

Then, you can cancel a lesson simply by calling lesson.cancel(), and it will default to cancelling it today. If you want to future cancel it, you can pass a date: lesson.cancel(date=tommorrow) (where tomorrow is a datetime). If you want to do other processing before saving, pass commit=False, and it won't actually save the object to the database yet. Then, call lesson.save() when you're ready.

like image 65
Chris Pratt Avatar answered Oct 21 '22 16:10

Chris Pratt


This is what I came up with. I feel that lessons_in_range() may not be as "Pythonic" as I could get it, but this does what I need it to do.

class Lesson(models.Model):
RECURRENCE_CHOICES = (
    (0, 'None'),
    (1, 'Daily'),
    (7, 'Weekly'),
    (14, 'Biweekly')
)
relatedLesson = models.ForeignKey('self', null=True, blank=True)
student = models.ForeignKey(Student)
frequency = models.IntegerField(choices=RECURRENCE_CHOICES, null=True, blank=True)
lessonTime = models.TimeField('Lesson Time', null=True, blank=True)
startDate = models.DateField('Start Date')
endDate = models.DateField('End Date', null=True, blank=True)
isCancelled = models.BooleanField(default = False)
amtBilled = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
amtPaid = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)

def get_exceptions(self):
    return Lesson.objects.filter(relatedLesson = self.id)

def cancel(self, date=None):
    if date:
        x = Lesson()
        x = self
        x.pk = None
        x.relatedLesson = self.id
        x.isCancelled = True
        x.startDate = date
        x.endDate = date
        x.save()
    else:
        self.endDate = datetime.date.today()
        self.save()
    return

def pay_lesson(self, date, amount):
    x = Lesson()
    x = self
    x.pk = None
    x.relatedLesson = self.id
    x.amtPaid = amount
    x.startDate = date
    x.endDate = date
    x.save()
    return

def lessons_in_range(self, startDate, endDate):
    if (self.startDate > endDate) or (self.endDate < startDate):
        return None
    if self.endDate < endDate:
        endDate = self.endDate
    ex = self.get_exceptions()
    if self.frequency == 0:
        if ex:
            return ex
        else:
            return self
    sd = next_date(self.startDate, self.frequency, startDate)
    lessonList = []
    while (sd <= endDate):
        exf = ex.filter(startDate = sd)
        if exf:
            # lesson already exists in database, add it
            lessonList.append(exf)
        elif sd == self.startDate:
            # lesson is the original lesson, add that
            lessonList.append(self)
        else:
            # lesson does not exist, create it in the database then add it to the list
            x = Lesson()
            x.student = self.student
            x.frequency = 0
            x.lessonTime = self.lessonTime
            x.relatedLesson = self
            x.startDate = sd
            x.endDate = sd
            x.isCancelled = False
            x.amtBilled = self.amtBilled    
            x.amtPaid = None
            x.save()
            lessonList.append(x)
        sd += timedelta(self.frequency)
    return lessonList
like image 1
Matthew Calabresi Avatar answered Oct 21 '22 14:10

Matthew Calabresi