2016-11-29 52 views
0

我有一個Django應用程序(1.8) 這裏是我的模型的一部分:代碼應該返回最小值,但它不

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') 

這裏是我的模型方法:

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]) 

我在模型中的值:

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

我的代碼應該返回900,但我得到1800,我不明白爲什麼。

+2

隨着' '{0}' 格式(I) '你把你的整數轉換成字符串! –

回答

4

min函數比較字符串而不是數字,因此按字母順序返回最小值。

嘗試:

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

作品,謝謝。 –

0

您需要將字符串轉換爲整數。

>>> prices = [4000, 2800, 1800, 900] 
>>> min(['{0}'.format(i) for i in prices if i is not None]) 
'1800' 
>>> min([int('{0}'.format(i)) for i in prices if i is not None]) 
900 
0

這爲我工作

>>> prices = [4000, 2000, 1800,900] 

>>> '{}'.format(min(prices)) 

'900' 
+0

雖然它很適合你...這並不能解釋操作系統有什麼問題 – Sayse