abctest
abctest

Reputation: 163

Django: how do you filter with dates and a foreign key

Inside of models I have:

  1. The Hotel Name
  2. The price for each night.

models.py:

class Hotel_Database(models.Model):
    hotel_name = models.CharField(max_length=20)

class Hotel_Date_Price(models.Model):
    hotel = models.ForeignKey(Hotel_Database, on_delete=models.CASCADE , related_name='hotel')
    checkin = models.DateField(default= datetime.date.today())  
    checkout = models.DateField(default=datetime.date.today() + datetime.timedelta(1))   
    price = models.IntegerField()

views.py:

import datetime
x = Hotel_Database.objects.get(id=1)
#the price for the night of June 26th:
Hotel_Date_Price.objects.create(hotel = x, checkin= datetime.date(2018, 6, 27), checkout=datetime.date(2018, 6,28), price=50).save()
#the price for the night of June 27th:
Hotel_Date_Price.objects.create(hotel = x, checkin= datetime.date(2018, 6, 28), checkout=datetime.date(2018, 6,29), price=50).save()


Hotel_Database.objects.filter(hotel_name__icontains='Hotel', hotel__checkin__lte=datetime.date(2018, 6, 27), hotel__checkout__gte=datetime.date(2018, 6, 28))
#results: <QuerySet [<Hotel_Database: Shangri-La>]>

Now here is what happens when I try to filter through more than one night:

Hotel_Database.objects.filter(hotel_name__icontains='Hotel', hotel__checkin__lte=datetime.date(2018, 6, 27), hotel__checkout__gte=datetime.date(2018, 6, 29))
#results: <QuerySet []> 
# it returns an empty list 

I am basically trying to change the price of each night

Upvotes: 0

Views: 802

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

Looks like you confused lte and gte. lte means less than, while gte is greater than. So you should use end date with lte condition and start date with gte:

Hotel_Database.objects.filter(hotel_name__icontains='Hotel', hotel__checkin__gte=datetime.date(2018, 6, 27), hotel__checkout__lte=datetime.date(2018, 6, 29))

Also note you don't need to call save() after create() method. You can just use create().

UPD

If you need to exclude hotels with specific period of checkin/checkout from queryset you can use exclude():

Hotel_Database.objects.filter(hotel_name__icontains='Hotel').exclude( hotel__checkin__gte=datetime.date(2018, 6, 27), hotel__checkout__lte=datetime.date(2018, 6, 29))

Upvotes: 3

Related Questions