drakenation
drakenation

Reputation: 412

How to find avaiable time slots in an Appointments table using Django ORM?

I have a Django model that models patients making Appointments with doctors, like so:

class Appointment(Model):
    doctor = models.ForeignKey(User)
    start = models.DateTimeField()
    finish = models.DateTimeField()
    ...

I want to find available time slots that have at least a certain length between a range of datetimes, like this:

def find_timeslots(timeslot_length, start_datetime, finish_datetime): 
    ....

Some observations:

My current solution is getting all Appointments from a doctor and iterate from start_datetime until finish_datetime in timeslot_length intervals, checking for conflicts. If it has no conflict, I store a (start, finish) tuple in a list.

It somewhat works, but it doesn't seems like an elegant solution. What's a better approach to this problem?

Upvotes: 1

Views: 2130

Answers (1)

Shahzeb Qureshi
Shahzeb Qureshi

Reputation: 612

Generate a unique slot ID for every appointment slot. You can make combination of date + time + doctorid as the slot ID (depends upon you). When you save an appointment save it with the slot id you generated and when you want to check for conflicts you need not iterate from start time to end time, just check whether the slot id you are about to save exists or not.

Upvotes: 1

Related Questions