更新
感谢 Root 的以下回答(我赞成)。根据您的建议,我能够解决我的问题。我现在正在使用这个 -
try:
queryset2 = RoomBookings.objects.filter(HotelName__HotelName__icontains=hotel.HotelName)
except:
pass
这是有效的 -
RoomBookings.objects.filter(HotelName__icontains=hotel.HotelName, RoomType__icontains= hotel.RoomType,
ArrivalDate__lt=RoomBookingsForm['DepartureDate'], DepartureDate__gt=RoomBookingsForm['ArrivalDate'])
但后来我将 RoomBookings 模型中的 HotelName 字段从 CharField 更改为 ForiegnKey。现在我无法弄清楚如何进行反向查找。这些是我失败的尝试-
# queryset2 = RoomBookings.objects.filter(HotelName__HotelName__icontains=hotel.HotelName)
# queryset2 = RoomBookings.objects.filter(HotelName__Hotel__HotelName__icontains=hotel.HotelName)
# queryset2 = RoomBookings.objects.filter(HotelName__Hotel__HotelName_exact=hotel.HotelName)
# queryset2 = RoomBookings.objects.filter(HotelName__HotelName_exact=hotel.HotelName)
class Hotel(models.Model):
HotelName = models.CharField(max_length=60, null=False)
def __str__(self):
return self.HotelName
class RoomType(models.Model):
HotelName = models.ForeignKey(Hotel, null=True, blank=True, on_delete=models.CASCADE)
RoomType = models.CharField(max_length=60, null=False, choices=Room_Type)
def __str__(self):
return '{0}, {1}'.format(str(self.HotelName), self.RoomType)
class RoomBookings(models.Model):
User = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
HotelName = models.ForeignKey(Hotel, null=True, blank=True, on_delete=models.CASCADE)
RoomType = models.CharField(max_length=60, null=False, choices=Room_Type)
def __str__(self):
return '{0}, {1}, {2}'.format(self.HotelName, self.ArrivalDate, self.RoomType)