Python 不会在简单的 "if" 语句中分配正确的值

Python won't assign the right value in simple "if" statement

我有一个 Django 项目,用户可以在其中创建预订。 我正在为 API 使用 Tastypie,我向其提交简单的 POST 请求,以便在数据库中创建预订。

假设我们有一个像这样的 request(from Chrome Network Tab)

{passenger_name: "John", service_time_start: "12:12:12", flight_time: "12:12:12",…}
car_type: false
passenger_email: "john@gmail.com"
passenger_lastname: "Smith"
passenger_name: "John"
passenger_number: "5"
route_end: "Los Angeles"
route_start: "New York"

我在服务器端使用这段代码(models.py)。
我想 将 car_type 分配给具有 Django Signals.

的实例
''' Change car type for new reservation '''
@receiver(pre_save, sender=Reservation)
def smart_car_options(sender, instance, *args, **kwargs):

    print 'SIGNAL: pass_no: ', instance.passenger_number
    print 'SIGNAL: car_type: ', type(instance.car_type)

    if instance.car_type == False:
        if instance.passenger_number <= 3:
            instance.car_type = 'CAR'
        if 4 < instance.passenger_number <= 8:
            instance.car_type = 'VAN'
        if instance.passenger_number > 8:
            instance.car_type = 'BUS'

    print "--------------------------------------------"
    print 'SIGNAL: pass_no: ', instance.passenger_number
    print 'SIGNAL: car_type: ', instance.car_type

如您所见,instance.car_type 被设置为 'BUS',而本应设置为 'VAN'我做错了什么?

此外,这是 request:

的控制台输出
[20/Mar/2015 02:10:21] "POST /api/reservation/ HTTP/1.1" 201 736
[20/Mar/2015 02:10:40] "GET /forms/as_shuttle/ HTTP/1.1" 200 16237
[20/Mar/2015 02:10:52] "GET /static/debug_toolbar/css/toolbar.css HTTP/1.1" 304 0
SIGNAL: pass_no:  5
SIGNAL: car_type:  <type 'bool'>
--------------------------------------------
SIGNAL: pass_no:  5
SIGNAL: car_type:  BUS
[20/Mar/2015 02:11:06] "POST /api/reservation/ HTTP/1.1" 201 732

看起来 passenger_number 设置正确,但它仍然不会 为实例分配正确的值。它总是分配最后一个值,'BUS'.

PS: 相同的代码在 django 管理中运行良好。

您可能没有将 passenger_number 转换为整数,因此比较运算符正在比较字符串和整数。

>>> "5" < 8
False
>>> "5" > 8
True

所以尝试 num_passengers = int(instance.passenger_number) 之类的东西,然后再与它进行比较。