I’m currently developing a Gym website and using django-recurrence to handle recurring training sessions.
However, I’m unsure how to work with recurrence dates in a Django QuerySet. Specifically, I want to sort trainings by the next upcoming date and filter trainings by a specific date, for example, to show sessions that occur on a selected day. What’s the best way to achieve this using django-recurrence?
Should I extract the next occurrence manually and store it in the model, or is there a more efficient approach for filtering and sorting recurring events? Any advice or examples would be greatly appreciated!
class Training(TimestampModel):
template = models.ForeignKey(TrainingTemplate, on_delete=models.CASCADE, related_name='trainings')
start_time = models.TimeField()
end_time = models.TimeField()
location = models.ForeignKey(TrainingLocation, on_delete=models.PROTECT, related_name='trainings')
recurrences = RecurrenceField()
members = models.ManyToManyField(Member, through=MemberTraining, related_name='trainings', blank=True)
objects = TrainingManager()
I have a few ideas on how to handle this, but they all feel a bit over complicated.
- Add a next_training_date field to the Training model and use a Celery ETA task to update this field every time the training ends.
For example, when an admin creates a new training, the next_training_date is calculated on save. Then, a scheduled Celery task (with ETA) is created to update this date again after the current session ends.
While this might work, it feels like too much overhead just to support filtering and sorting by recurrence dates.
What would you recommend as a clean and efficient way to handle recurrence and QuerySet filtering using django-recurrence? Is there a better pattern or approach for dealing with recurring events in Django?