Search code examples
pythondjangodjango-admintastypiedjango-signals

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


I have a Django project where users can create reservations. I am using Tastypie for the API to which I submit simple POST request to in order to create a reservation in the database.

Let's say we have a request like this(from Chrome Network Tab)

{passenger_name: "John", service_time_start: "12:12:12", flight_time: "12:12:12",…}
car_type: false
passenger_email: "[email protected]"
passenger_lastname: "Smith"
passenger_name: "John"
passenger_number: "5"
route_end: "Los Angeles"
route_start: "New York"

I'm using this code(models.py) at the server-side.
I want to assign a car_type to the instance with 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

As you can see, the instance.car_type is beeing set to 'BUS', when it should be set to 'VAN'. What am I doing wrong?

Also, here is my console output for the 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

It looks like passenger_number is beeing set correctly, but it still won't assign the right value to the instance. It's always assigning the last value, 'BUS'.

PS: The same code is working fine in the django admin.


Solution

  • It may be that you are not converting passenger_number to an integer so the comparison operators are comparing between a string and an integer.

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

    So try something like num_passengers = int(instance.passenger_number) and then do your comparisons against that instead.