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)
What it does: It autogenerates a number in the format '1/year' '2/year' etc. If the user introduces other number, p.e. 564/10 the function follows it and the next will be 565/10.
Even if the user introduces p.e. 34/10 after the entry with 564/10 the function will follow the largest number.
Did I do this right or there's a better way to do it?
Update:
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)