当某个时间值从false回到true

when a certain time value comes from false back to true

我需要在它来的时候自动制作leave_date(leaved date)room_bool == True现在都通过urls.py/get/by/<int:pk>

完成了

views.py

    date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    reg = Registration.objects.get(rooms_id=pk)
    room = Rooms.objects.get(pk=pk)
    a = reg.leave_date.replace(tzinfo=None) >= datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S').replace(
        tzinfo=None)
    if a != True:
        reg.room_bool = True
        reg.save()
        room.room_bool = True
        room.save()

models.py

    room_num = models.IntegerField()
    room_bool = models.BooleanField(default=True) #if room_bool = True room is open, else closed.
    category = models.CharField(max_length=150)

    def __str__(self):
        return f'{self.room_num}'

    class Meta:
        verbose_name = 'Room'

#This class Registration for visitors, to open room for the them
class Registration(models.Model):
    rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    admin = models.ForeignKey(User, on_delete=models.CASCADE)
    pasport_serial_num = models.CharField(max_length=100)
    birth_date = models.DateField()
    img = models.FileField()
    visit_date = models.DateTimeField()
    leave_date = models.DateTimeField()
    guest_count = models.IntegerField()

    def func(self):
        room = Rooms.objects.filter(room_bool=True)
        for i in room:
            if i.room_num == int(self.rooms):
                i.room_bool = False #this should change when adding new registration
                i.save()

你需要一些东西来控制时间,这并不容易实现。

更简单的方法是创建名为 Reservation 的模型或您喜欢的名称。然后,如果有人保留 - 创建该对象。房间可以通过方法查看预订。

class Reservation(...):
    room = models.ForeignKey(...)
    start_date = models.DateTimeField(...)
    end_date = models.DateTimeField(...)
    ...

class Room(...):
    ...

    def is_avaiable(self, date):
        return not self.reservation_set.filter(start_date__gte=date, end_date__lte=date)

也可以使用类似 apscheduler. Longer way is to use Celery 的方法,但仅当您计划在许多应用程序中执行大量此类操作时才使用它。