简体   繁体   中英

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM