如何从 Django 中的查询集中删除对象

问题描述 投票:0回答:0

房间由预定义的时间段组成,客户可以预订任何时间段。

模型,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)

房间管理员可以看到所有时间段的列表,也可以过滤它们。

表格.py

class SearchTimeSlotsForm(forms.Form):

    date = forms.DateField(widget=FutureDateInput(attrs={'class': 'unbold-form'}), required=False, initial=date.today())
    available_from = forms.TimeField(widget=TimeInput(attrs={'class': 'unbold-form'}), required=False)
    available_till = forms.TimeField(widget=TimeInput(attrs={'class': 'unbold-form'}), required=False)

    STATUS = (
        (None, 'Any'),
        ('Vacant', 'Vacant'),
        ('Booked', 'Booked'),
    )
    occupancy = forms.ChoiceField(
        required=False,
        widget=forms.RadioSelect(attrs={'class': 'unbold-form'}),
        choices=STATUS,
    )

    SORT = (
        ('available_from', 'Ascending'),
        ('-available_from', 'Descending'),
    )
    sort_by = forms.ChoiceField(
        widget=forms.Select(attrs={'class': 'unbold-form'}),
        choices=SORT,
    )

    """Function to ensure that booking is done for future and check out is after check in"""
    def clean(self):
        cleaned_data = super().clean()
        available_from = cleaned_data.get("available_from")
        available_till = cleaned_data.get("available_till")

        if (available_from is not None and available_till is None) or (available_from is None and available_till is not None):
            # Raising a ValidationError that refers to a specific
            # field so the error is better pointed out to the user.
            raise ValidationError(
                _("You can either fill both 'Available from' and 'Available till' or choose not to fill both of them."),
                code='invalid'
            )

        str_available_from = str(available_from)
        str_available_till = str(available_till)
        format = '%H:%M:%S'
        if available_from is not None:
            try:
                datetime.strptime(str_available_from, format).time()
                datetime.strptime(str_available_till, format).time()
            except Exception:
                raise ValidationError(
                    _('Wrong time entered.'),
                    code='Wrong time entered.',
                )
            if available_till <= available_from:
                raise ValidationError(
                    "Available till should be after available from.", code='Available till after available from'
                )

在“入住率”中,客房经理可以选择“任何”、“空置”或“已预订”。 time_slots 包含基于所选条件的所有时隙的查询集。

例如

time_slots = , , ]>

我可以在 HTML 中呈现时间段,但问题是占用率。

为了找到入住率,我必须执行以下操作。

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 中呈现时间段?

python django django-queryset
© www.soinside.com 2019 - 2024. All rights reserved.