How to auto increament unique number with a prefix ?

how can i increment an invoice number with a prefix “INV” and number that increments ‘0001’, ‘0002’, ‘0003’ when the user creates an invoice?

my model

class Invoice(model.Models):
        clients_name = models.ForeignKey(Clients, on_delete=models.CASCADE, blank=True,null=True)
        invoice_number = invoice_number = models.CharField(max_length=200, blank=True, null=True)

Table
once the user creates the invoice, the hidden field(invoice field) should be autofilled with invoice number, e.g

client invoice
client_name1 INV-001
client_name2 INV-002
client_name4 INV-003
client_name8 INV-004

Hi kenkennie!
I think the problem lies in the algorithm, not the technology platform, language or framework.
You can use .zfill(n) to add n-1 zeros in front of the string. Then add INV in front
eg:

# get last item
item = Invoice.objects.filter(invoice_number__istartswith='INV').order_by('-create_date')[0]
# last index
index = int(item['invoice_number'][-3:]) # = int('003') = 3

res = 'INV-' + str(x+1).zfill(3)
# res = 'INV-004'

Sorry to ask. This should be in models.py or views.py? if you could write the function i would really appreciate
i am new to django building my first project

You don’t want to try and do this “manually”. (See any of the discussions on here about trying to create unique IDs.)

Create an AutoField to keep the numeric portion, or just use the ID field, and add the text prefix for those situations where it’s needed.

(Precisely how you may want to do this depends upon all the situations where that specific-formatted value is going to be used.)

You can write in models.py, but this solution is manual. As KenWhitesell said: it should be automation. You can refer to his solution.

1 Like