def __number():
# This line returns the number of the latest created object
# as a "Factura" object in format "n/year"
last = Factura.objects.filter(f_type__exact=False).latest('number')
# We convert it into a string and split it to get only the first number
spl = str(last).split('/')[0]
# Convert it into integer so we can do math
n = int(spl)
# Get the current year
y = date.today().strftime('%y')
# If none return 1/year
if n == None:
return str(1) + '/' + str(y)
# Else we increment the number in one.
else:
n = n + 1
return str(n) + '/' + str(y)
它做什麼:它會自動生成格式爲'1/year''2/year'的數字等等。如果用戶引入了其他數字,p.e. 564/10功能跟隨它,下一個將是565/10。任何方式來改善這個python函數?
即使用戶介紹p.e.在與564/10的輸入之後的34/10功能將遵循最大數量。
我做對了嗎?還是有更好的方法來做到這一點?
更新:
def __number():
current_year = date.today().strftime('%y')
try:
facturas_emmited = Factura.objects.filter(f_type__exact=False)
latest_object = facturas_emmited.latest('number').__str__()
first_number = int(latest_object.split("/")[0]) + 1
except Factura.DoesNotExist:
first_number = 1
return '%s/%s' % (first_number, current_year)
.....使用PERL! – 2010-06-30 20:00:31
@Greg我最好自殺......嘿嘿。 Perl對我來說太高級了,也許將來我會試着去學習它。 – 2010-06-30 20:03:45
不要使用裸''except'塊,只抓住你擔心的具體錯誤 – Daenyth 2010-06-30 20:37:36