# Create Custom Invoice Id

**URL:** <https://forum.djangoproject.com/t/create-custom-invoice-id/29601>\
**Category:** Using the ORM\
**Created:** [March 29, 2024, 5:03am UTC](https://forum.djangoproject.com/t/create-custom-invoice-id/29601 "2024-03-29T05:03:53Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ahmed7fathi](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ahmed7fathi/32/10243_2.png) [@Ahmed7fathi](https://forum.djangoproject.com/u/Ahmed7fathi)\
**Post date:** [March 29, 2024, 5:03am UTC](https://forum.djangoproject.com/t/create-custom-invoice-id/29601/1 "2024-03-29T05:03:53Z")

</div>

I’m afraid my solution will duplicate invoice \_d if 2 users make invoices on stock at the same time  
how can I prevent this I read about select\_for\_update but I don’t know what is the right place to implement it

```auto
class Order(models.Model):
    invoice_id = models.CharField(max_length=20)
    stock = models.ForeignKey(Stock, on_delete=models.CASCADE)
    
    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['invoice_id', 'stock'],
                                    name='Order Id Already exists With a Stock'),
        ]

    def generate_invoice_id(self):
        # Get the count of existing invoices of stock and add 1
        sequential_number = self.stock.order_set.count() + 1
        return f'INV-{sequential_number}' # format: INV-123

    def save(self, *args, **kwargs):
        if not self.invoice_id:
            self.invoice_id = self.generate_invoice_id()
            super().save(*args, **kwargs)

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 29, 2024, 11:35am UTC](https://forum.djangoproject.com/t/create-custom-invoice-id/29601/2 "2024-03-29T11:35:06Z")

</div>

> [@Ahmed7fathi](#):
>
> ```auto
> def generate_invoice_id(self):
> # Get the count of existing invoices of stock and add 1
> sequential_number = self.stock.order_set.count() + 1
> return f'INV-{sequential_number}' # format: INV-123
> 
> ```

This is a bad idea for a number of reasons. And yes, the chance that this method generates a duplicate value will increase over time.

I’d first ask the question, “Is it _really_ a **requirement** that invoice numbers be sequential and without gaps?” If that is the case, you have a much bigger issue that needs to be addressed. (Like answering the question, _why_ is _this_ so important.)

Otherwise, I’d suggest just using the `id` field on the model as your “sequential\_number”. It doesn’t even need to be stored in the database as a separate entity - you can add a model method to generate it as needed when it’s needed to be displayed.

Beyond that, if there is a _valid_ reason to segregate invoice numbers by `Stock`, you could add a field on `Stock` for `current_invoice_number`, with a model method that within a transaction does the `select_for_update` to get the `Stock` instance, increment the field, save it to the database, and return the value.

---

<div class="post-metadata">

**Author:** ![Ahmed7fathi](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ahmed7fathi/32/10243_2.png) [@Ahmed7fathi](https://forum.djangoproject.com/u/Ahmed7fathi)\
**Post date:** [March 29, 2024, 6:13pm UTC](https://forum.djangoproject.com/t/create-custom-invoice-id/29601/3 "2024-03-29T18:13:47Z")

</div>

> Is it _really_ a **requirement** that invoice numbers be sequential and without gaps?

Ok I need to do this because every user can have multiple stocks when users create invoices from different stocks the invoice ID will be sequential which is not right user A has nothing to do with **User B** invoices.  
**User A** creates an invoice with id 1 the **user B** invoice id will be 2

I want every stock ID order to be unique in its stock

the other reason if the order fails the invoice will reserve the ID if the order ID 1 fails the next order ID will be 2 which is not ideal transaction will not help in this case because I need to save the order first for some operations

If I understand your solution correctly it would be like this

```auto
class Stock(models.Model):
    current_invoice_number = models.IntegerField(default=0)

```

```auto
class Order(models.Model):
    def generate_invoice_id(self):
        with transaction.atomic():
            stock_instance = Stock.objects.select_for_update().get(id=self.stock.id)
            current_invoice_number = stock_instance.current_invoice_number
            new_invoice_number = current_invoice_number + 1
            stock_instance.current_invoice_number = new_invoice_number
            stock_instance.save()
            return f'INV-{new_invoice_number}'

    def save(self, *args, **kwargs):
        if not self.invoice_id:
            self.invoice_id = self.generate_invoice_id()
            super().save(*args, **kwargs)

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 29, 2024, 7:58pm UTC](https://forum.djangoproject.com/t/create-custom-invoice-id/29601/4 "2024-03-29T19:58:11Z")

</div>

> [@Ahmed7fathi](#):
>
> the invoice ID will be sequential which is not right user A has nothing to do with **User B** invoices.

Agreed. But who cares?

Making them strictly sequential adds a constraint that will need to prevent any two people from creating two invoices for a single stock at the same time. (If you allow for concurrent or near concurrent submission, then you need to single-thread this submission process to prevent a transaction failure from creating a gap in your numbers.)

> [@Ahmed7fathi](#):
>
> If I understand your solution correctly it would be like this

Basically, yes. But this still doesn’t prevent gaps.

---

<div class="post-metadata">

**Author:** ![Ahmed7fathi](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ahmed7fathi/32/10243_2.png) [@Ahmed7fathi](https://forum.djangoproject.com/u/Ahmed7fathi)\
**Post date:** [March 29, 2024, 9:35pm UTC](https://forum.djangoproject.com/t/create-custom-invoice-id/29601/5 "2024-03-29T21:35:28Z")

</div>

> Agreed. But who cares?

it’s the client’s requirement

> [@KenWhitesell](#):
>
> Making them strictly sequential adds a constraint that will need to prevent any two people from creating two invoices for a single stock at the same time

could you please provide me with how to do it?

---

<div class="post-metadata">

**Author:** ![graceturner56](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/graceturner56/32/19641_2.png) [@graceturner56](https://forum.djangoproject.com/u/graceturner56)\
**Post date:** [April 10, 2024, 10:24am UTC](https://forum.djangoproject.com/t/create-custom-invoice-id/29601/6 "2024-04-10T10:24:09Z")

</div>

Find out How to Customize [Invoice in Odoo](https://www.theledgerlabs.com/odoo-customize-invoice/)? Visit Ledger Labs

---

<div class="post-metadata">

**Author:** ![jonathanLynn](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jonathanlynn/32/20517_2.png) [@jonathanLynn](https://forum.djangoproject.com/u/jonathanLynn)\
**Post date:** [April 10, 2024, 10:54am UTC](https://forum.djangoproject.com/t/create-custom-invoice-id/29601/7 "2024-04-10T10:54:38Z")

</div>

Would adding your invoices to a queue help where you have a background task that picks up the invoice one at a time and generates the invoice number? Means multiple users can raise invoices and you have a process to handle the load without risking duplicate invoice numbers?
