I need to create an auto increasing invoice number starting from 000001 and going up ex.000001, 000002, 000003 and so on right now i have this code that i took from another stack overflow question but i dont want the MAG part
def increment_invoice_number(self):
last_invoice = Transaction.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
invoice_int = int(invoice_no.split('MAG')[-1])
new_invoice_int = invoice_int 1
new_invoice_no = 'MAG' str(new_invoice_int)
return new_invoice_no
invoice_no = models.CharField(max_length=500, default=increment_invoice_number, null=True, blank=True)
i want my invoice num to start with 000001
CodePudding user response:
You can use an IntegerField
instead of a CharField
for the invoices:
from django.db.models import Max
def invoice_number():
invid = Invoice.objects.aggregate(
max_inv=Max('invoice_no')
)['max_inv']
if invid is not None:
return invid 1
return 0
class Invoice(models.Model):
invoice_no = models.IntegerField(default=invoice_number, unique=True, editable=False)
We thus determine the maximum value for invoice_no
, and then assign this as default value for the invoice_no
of our Invoice
model.
unique=True
will prevent having two (or more) invoices with the same invoice_no
. If there is a race condition, then one of the two views will error on this. You thus can implement a retry mechanism to eventually assign a valid invoice number.
By making it editable=False
, this will not appear in the ModelForm
s and ModelAdmin
s for the Invoice
model. You can omit this if the form should make the field editable.