I am implementing a monthly calendar in django and used some code I found online. Within the code there is a lambda function that I need to tune for my specific use.
def group_by_day(self, event):
field = lambda event: event.start.day
return dict(
[(day, list(items)) for day , items in groupby(event, field)]
)
From what I read online:
group_by_day() builds a dictionary with the day of the month as key and any workouts for that day as its value (http://uggedal.com/journal/creating-a-flexible-monthly-calendar-in-django/)
Im quite new to python and having problem figuring out how its actually doing its magic. I do understand that it uses the event.start.day
to assign it to a day and month. Is it doing this with recursion?
I'm trying to tune the function so it would support recurring/multi-day events.
Thanks
All the lambda does is return the day portion of the event start date;
lambda
objects are just functions. The real magic is in theitertools.groupby()
function, which produces groups based on that return value. Each time the value changes from one event to the next, you get a new group.Depending on how your multiday / recurrence is implemented, it probably is not going to be easy to adapt this directly to your case. You'd have to switch to a loop with a dictionary instead.
Here is an equivalent function using just a loop, which will be easier to adapt:
This is not dependent on the order of the events as it'll just group every date by the day regardless of where it appears in the sequence. This should let you add an event to more than one day.