0

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
KENnie
  • 1
  • 4

1 Answers1

1

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.

Lucas Grugru
  • 1,664
  • 1
  • 4
  • 18
  • What if someone calls .save() on existing invoice? Wouldn't that change invoice_number? – PTomasz Nov 23 '22 at 10:52
  • @TrueGopnik Correct ! I edited for saving only in creation and if the invoice_number has not already set manually – Lucas Grugru Nov 23 '22 at 10:55
  • Thanks for edit, on the side note this looks more like something to be done in __str__ or separate property than separate field in DB – PTomasz Nov 23 '22 at 10:57
  • i do not understand your remark. The author can use another field in DB for storing the current number or retrieve this number by spliting the invoice_number field. – Lucas Grugru Nov 23 '22 at 11:03
  • To create invoice_number You need two things: "INV-" string and PK of related invoice. If we create property called invoice_number, we could describe this field as: f"INV-{str(self.pk).zfill(3)}" This way we can access invoice number without creating separate column. It's not attack on your question, it does required job pretty well, just my side note. – PTomasz Nov 23 '22 at 11:13