Django - Find reserved times

I would like to show all the available times for the not booked appointment dates with a time interval between 11:00AM to 21:00PM:

models.py

class Appointment(models.Model):
    
    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    seat = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True)
    work = models.ManyToManyField(Therapy, related_name='work', verbose_name=_('Work'), blank=True)
    start_appointment = models.DateTimeField(default=timezone.now, blank=True)
    end_appointment = models.DateTimeField(default=timezone.now, blank=True)

views.py

    def check_available_hours(request):
        day_request = date.today()
        day_request1 = str(day_request)
        date_of_reference = datetime.strptime(day_request1, "%Y-%m-%d")
    
        initial_time = datetime.combine(date_of_reference.date(), time(11, 0))
        final_time = datetime.combine(date_of_reference.date(), time(21,0))
    
        appointments_of_day = Appointment.objects.filter(
            start_appointment__gte=initial_time,
            start_appointment__lte=final_time
        )
        print(appointments_of_day) # This returns all appointments in a day
    
        reserved_times = [datetime(2021, 12, 8, 11, 0), datetime(2021, 12, 8, 15, 0)]
    
        hours_between = [datetime.combine(date_of_reference.date(), time(hour + initial_time.hour, 0)) for hour in range(((final_time - initial_time).seconds // 3600) + 1)]
    
        available_hours = [hour for hour in hours_between if hour not in reserved_times]

        return render(request, "name_template.html", {"hours": avaliable_hours})

If i set reserved_dates like above it works. However i'm trying to set it based on my models so i used below code but it doesn't return anything.

reserved_times = []
for appointment in appointments_of_day:
    for i in range((appointment.end_appointment - appointment.start_appointment).seconds//3600):
        reserved_times.append(appointment.start_appointment + timedelta(hours=i))
print(reserved_times)

Any suggestions?

Thank you

Back to Top