Home > database >  Python Django - unsupported operand type(s) for -: 'float' and 'NoneType'
Python Django - unsupported operand type(s) for -: 'float' and 'NoneType'

Time:09-05

I'm a beginner to python and Django, I tried to do searching but I can't find my answer to this. Can anybody help me with this please.

code from my html:

<td >
{{ schedule.count_available|floatformat:0|intcomma }}
</td>

my model:

class Schedule(models.Model):
    code = models.CharField(max_length=100)
    vessel = models.ForeignKey(Vessel,on_delete=models.CASCADE)
    depart = models.ForeignKey(Location,on_delete=models.CASCADE, related_name='depart_location')
    destination = models.ForeignKey(Location,on_delete=models.CASCADE, related_name='destination')
    schedule= models.DateTimeField()
    fare= models.FloatField()
    status = models.CharField(max_length=2, choices=(('1','Active'),('2','Cancelled')), default=1)
    date_created = models.DateTimeField(default=timezone.now)
    date_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.code   ' - '   self.vessel.vessel_number)

    def count_available(self):
        booked = Booking.objects.filter(schedule=self).aggregate(Sum('seats'))['seats__sum']
        return self.vessel.seats - booked

error: error image

CodePudding user response:

The error appear when booked value is None. You should debug your code.

Is your query Booking.objects.filter(schedule=self) have at least one value

CodePudding user response:

The error occur when django encounter schedule object that have no booking, and in such case

booked = Booking.objects.filter(schedule=self).aggregate(Sum('seats'))['seats__sum']

evaluates to None and raise the error

To solve this, update your count_available method as follows

def count_available(self):
    booked = Booking.objects.filter(schedule=self).aggregate(Sum('seats'))['seats__sum']
    if booked:
        return self.vessel.seat - booked
    return self.vessel.seats

This will only do the substraction when bookings for that schedule is available, otherwise returns the total number of seats for the schedule

  • Related