1

I'm trying to show my posts for a specific time here is my models.py

class Booking(models.Model):
    check_in = models.DateTimeField(default=timezone.now)
    check_out = models.DateTimeField(blank=True,null=True)

i want display object for 12 hours after check out for example if we have an object its check out is 14/10/2021 10AM then show that post till 10PM !

i tried it , but didnt work Booking.objects.filter(check_out__hour=12)

is it possible please ? thank you in advance

artiest
  • 554
  • 5
  • 20

1 Answers1

1

You can filter with:

from datetime import timedelta
from django.db.models.functions import Now

Booking.objects.filter(
    check_out__gte=Now()-timedelta(hours=12)
)

you can filter further such that no objects with a check_out that is later than now are filtered out with a __range lookup [Django-doc]:

from datetime import timedelta
from django.db.models.functions import Now

Booking.objects.filter(
    check_out__range=(Now()-timedelta(hours=12), Now())
)

Here Now() is the timestamp of the database.

We can also work with the timestamp of the webserver machine with:

from datetime import timedelta
from django.utils.timezone import now

Booking.objects.filter(
    check_out__range=(now()-timedelta(hours=12), now())
)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • thank you for your response , but it returns all other objects which its checkout greater than current time , i want to only a specific range `check_out+12 hour`then make range between current time with checkout time should be only 12 hours – artiest Oct 14 '21 at 18:20
  • 1
    @HunarMohammed: then you should filter with a `__range`, see edit (last two code fragments) – Willem Van Onsem Oct 14 '21 at 18:23
  • can you take a look at this question please ? i need to set default hour for dateimte field https://stackoverflow.com/questions/69326480/how-to-set-default-hour-for-my-django-datetimefield – artiest Oct 14 '21 at 18:44