def calculate_mpg(self):
"""
Calculate ``calculated_mpg`` field.
:returns: True if recalculate, False if unable to calculate
:rtype: bool
"""
if self.gallons is None:
logger.warning(
'Gallons is none; cannot recalculate MPG for %s', self
)
return False
if self.odometer_miles is None:
logger.warning(
'odometer_miles is none; cannot recalculate MPG for %s', self
)
return False
prev = self._previous_entry()
if prev is None:
logger.warning('Previous entry is None; cannot recalculate MPG '
'for %s', self)
return False
distance = self.odometer_miles - prev.odometer_miles
self.calculated_miles = distance
self.calculated_mpg = (
(distance * Decimal(1.0)) / self.gallons
).quantize(Decimal('.001'), rounding=ROUND_FLOOR)
logger.debug('Calculate MPG for fill %d: distance=%s mpg=%s',
self.id, distance, self.calculated_mpg)
inspect(self).session.add(self)
评论列表
文章目录