Search code examples
djangodjango-modelsauto-increment

How to auto increment unique number with a prefix?


How can I increment an invoice number with a prefix “INV” and number that increments ‘0001’, ‘0002’, ‘0003’......and so on..... when the user creates an invoice?

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)

Once the user creates/saves the invoice form, the hidden field(invoice field) should be auto-filled with invoice number

e.g.

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

Solution

  • You can make this process in save model method:

    class Invoice(model.Models):
            clients_name = models.ForeignKey(Clients, on_delete=models.CASCADE, blank=True,null=True)
            invoice_number = models.CharField(max_length=200, blank=True, null=True)
    
        def save(self):
            if not self.invoice_number and self.pk is None:
                last_invoice = Invoice.objects.all().order_by("-pk").first()
                last_pk = 0
                if last_invoice:
                    last_pk = last_invoice.pk
            
                self.invoice_number = "INV-" + str(last_pk+1).zfill(3)
    
            super(Invoice, self).save()
    
    

    I am using the primary key for incremental number, but you can use another field in the model for making this task.