git-e git-e - 11 days ago 5
Python Question

Code should return min value but it doesn't

I have a django app (1.8)
Here is part of my model:

price_1 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_1')
price_2 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_2')
price_3 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_3')
price_4 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_4')
price_5 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_5')
price_6 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_6')
price_7 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_7')


Here is my method in model:

def min_prices(self):
prices = [self.price_1, self.price_2, self.price_3, self.price_4, self.price_5, self.price_6, self.price_7]
return min(['{0}'.format(i) for i in prices if i is not None])


My values in model:

price 1: 4000
price 2: 2800
price 3: 1800
price 4: 900


My code should return 900 but I got 1800 and I do not get why.

Answer

The min function is comparing strings rather than numbers and so returning the smallest alphabetically.

Try:

return str(min([price for price in prices if price]))