views:

488

answers:

2

I am working on a calendar application in django and want to support events which repeat an infinite amount of times after a given start date. I will store "block events" where each block includes data about a certain event (title, description...) as well as the pattern with which it repeats and an "expiration date". This way I only store one record for a group of possibly hundreds of repeated instances of an event. If I want to make an "exception", I can split this event block around the exception and have each block linked to previous and future blocks.

My problem is that I want to be able to run queries to fetch all of the "logical events" within a given time period as if a new event record was inserted for each instance of a repetition. Essentially I want to reveal a django model for each event to my application (and django's admin app), but store a single, different, model for each group of events in my database. Is this possible, and if so.. how? Or is there a better approach to repeating events?

+1  A: 

One possible approach is to have two different models. Your events are just as you've got them. Then have a "timespan" model. You could then use the start and end of the timespan to grab all the relevant events that fall within the span. If you're showing a non-flexible arrangement, the timespan model may actually be a "CalendarDay", and then a "Calendar" model could hold a week (or month, or whatever) of CalendarDays and use that information to get the proper set of events.

Harper Shelby
+2  A: 

Take a look at django-schedule, which has already implemented a system for this. They use a Period class that knows how to collect individual event occurrences within a given timeframe, and thus they can support infinite recurrence.

If you want to manifest real individual model objects in the Django admin for each occurrence of a recurring event, that's possible too, but you'll have to give up supporting infinite recurrence (you simply can't generate an infinite number of model objects). I implemented this for one project: each individual Occurrence object had an optional ForeignKey to a Recurrence model, which stored the metadata about the recurrence (i.e. "weekly on Mondays starting at this date"). In the save() method of the Recurrence object I would delete or create any of its linked Occurrences necessary to match its new data.

The first solution is a superior general solution to the problem, but you may have to do more UI work yourself, as you can't make every Occurrence into an actual model instance.

Carl Meyer