我有一个名为time_slots的QuerySet,其中包含模型类TimeSlot的对象。
time_slots = <QuerySet [
<TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 01:00:00, till: 02:00:00>,
<TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 04:07:00, till: 06:33:00>,
<TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 09:22:00, till: 10:55:00>
]>
模型、py
class Room(models.Model):
class Meta:
ordering = ['number']
number = models.PositiveSmallIntegerField(
validators=[MaxValueValidator(1000), MinValueValidator(1)],
primary_key=True
)
CATEGORIES = (
('Regular', 'Regular'),
('Executive', 'Executive'),
('Deluxe', 'Deluxe'),
)
category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular')
CAPACITY = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
)
capacity = models.PositiveSmallIntegerField(
choices=CAPACITY, default=2
)
advance = models.PositiveSmallIntegerField(default=10)
manager = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models. CASCADE
)
class TimeSlot(models.Model):
class Meta:
ordering = ['available_from']
room = models.ForeignKey(Room, on_delete=models.CASCADE)
available_from = models.TimeField()
available_till = models.TimeField()
"""class used when a user books a room slot."""
class Booking(models.Model):
customer = models.ForeignKey(User, on_delete=models.CASCADE)
check_in_date = models.DateField()
timeslot = models.ForeignKey(TimeSlot, on_delete=models. CASCADE)
每个时段可以被预订或空。为了找到它是被预订还是空的,我做了以下操作-
if request.session['occupancy'] == '':
for time_slot in time_slots:
try:
Booking.objects.get(check_in_date=request.session['date'], timeslot=time_slot)
time_slot.occupancy = "Booked"
except Exception:
time_slot.occupancy = "Vacant"
elif request.session['occupancy'] == 'Vacant':
for time_slot in time_slots:
try:
Booking.objects.get(check_in_date=request.session['date'], timeslot=time_slot)
time_slot.delete()
except Exception:
time_slot.occupancy = "Vacant"
elif request.session['occupancy'] == 'Booked':
for time_slot in time_slots:
try:
Booking.objects.get(check_in_date=request.session['date'], timeslot=time_slot)
time_slot.occupancy = "Booked"
except Exception:
time_slot.delete()
我必须根据占用状态在HTML中呈现时间段,占用状态可以是Any("),预订或空置。
我知道上面的代码不会工作,但我只是想告诉逻辑。我想知道如何根据占用率在HTML中呈现time_slots ?
如果我理解正确的话,下面应该可以解决你的问题。
它会添加"占用"字段,具体取决于在给定日期是否存在链接预订。
如果需要,这个占用字段将用于过滤
my_date = request.session["date"]
timeslots = TimeSlot.objects.annotate(occupancy=Case(When(booking_set__date=my_date, then="Booked"), default="Vacant"))
my_occupancy = request.session["occupancy"]
if my_occupancy != "":
timeslots = timeslots.filter(occupancy=my_occupancy)
注:booking_set__date=my_date
中的booking_set
为默认的related_name。你应该重写它
class Booking(models.Model):
customer = models.ForeignKey(User, on_delete=models.CASCADE)
check_in_date = models.DateField()
timeslot = models.ForeignKey(TimeSlot, on_delete=models. CASCADE, related_name=timeslots)