Home > Software design >  when a certain time value comes from false back to true
when a certain time value comes from false back to true

Time:05-25

I need to make it automatically when it comes leave_date(leaveted date) room_bool == True now it's all done via 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()

CodePudding user response:

You need something to control timing, it's not easy achieved.

Easier way is to create model called Reservation or something u prefer. Then if someone reserved - create that object. Room can check reservations with methods.

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)

Alternatively use something like apscheduler. Longer way is to use Celery, but use it only if you plan to have a lot of actions like this in many apps.

  • Related