【问题标题】:Django - Error while trying to iterate a model class (db table) in views.py (need to compare dates)?Django - 尝试在views.py中迭代模型类(数据库表)时出错(需要比较日期)?
【发布时间】:2020-11-12 14:28:55
【问题描述】:

这个想法是将检查日期和结帐日期与从 html 文件中获得的检查日期和结帐日期进行比较(酒店预订,我正在尝试查看是否有可用的 habitaciones [房间])

****views.py 中的代码 *****

定义保留(请求):

pickerR = request.POST.get('pickerR', None)

pickerR_checkout = datetime.datetime.strptime(pickerR, '%d/%m/%Y') #convierto la fecha de tipo string a datetime

pickerL = request.POST.get('pickerL', None)

pickerL_checking = datetime.datetime.strptime(pickerL, '%d/%m/%Y')  #convierto la fecha de tipo string a datetime

habitaciones = Habitacion.objects.all()

for hd in habitaciones:
    if Habitacion[hd].fecha_checkout >= pickerL_checking and  pickerR_checkout <= Habitacion[hd].fecha_checking:
        cantHabitaciones = `enter code here`int(request.POST.get('cant_habitaciones'))
        cantH = (request.POST.get('cant_huespedes'))
        tipo_habitaciones = models.tipoHabitacion.objects.all()

#code in models.py

类 Habitacion(models.Model):

precio = models.IntegerField()    
numero = models.IntegerField()
disponible = models.BooleanField()
tipo = models.ForeignKey(tipoHabitacion, on_delete=models.CASCADE)
fecha_checking = models.DateField('%d/%m/%Y')
fecha_checkout = models.DateField('%d/%m/%Y')

错误信息:

请求方法:POST 请求网址:http://127.0.0.1:8000/reservas.html/ Django 版本:3.1.1 异常类型:TypeError

异常值:'ModelBase' 对象不可下标

异常位置:/home/yamil/adaw2/hotel-Django/hotel/hotel/hotelApp1/views.py,第 94 行,预留 Python 可执行文件:/usr/bin/python3 Python 版本:3.8.5

  1. 如果 Habitacion[h].fecha_checkout

提前谢谢!!!

【问题讨论】:

  • 您应该将代码和错误作为文本添加到帖子正文中 - 而不是图片。

标签: python django model


【解决方案1】:

问题可能出在您迭代 habitaciones 的方式上。

您查询:

habitaciones = Habitacion.objects.all()

但是,当您遍历该列表时,您将对象放入对象本身(Habitacion 不是列表,它是一个模型):

如果 Habitacion[h].fecha_checkout >= pickerL_checking...

尝试像这样替换它:

如果 h.fecha_checkout >= pickerL_checking 和 pickerR_checkout

如果有帮助,请告诉我。

【讨论】:

    猜你喜欢
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2011-04-02
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多