0

IS there a method to make Django check for missing id number and create a new item in this slot, instead of making it with a new id.

Here is what am trying to do

I have the model :

class BuyInvoice(models.Model):
    date = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=PROTECT)
    branch = models.ForeignKey(Branch, on_delete=PROTECT)
    supplier = models.ForeignKey(Supplier, on_delete=PROTECT)
    total = models.PositiveIntegerField(default=0)
    is_done = models.BooleanField(default=False)
    is_canceled = models.BooleanField(default=False)

    def __str__(self):
        return 'فاتورة بيع رقم ' + str(self.pk)

whenever I add a new item to it it takes the auto-generated id as 1, 2, 3, 4, 5

now if I deleted the item with the id 3, then I try to create new item I want it to be added to the id of 3 instead of 6

Ahmed Wagdi
  • 3,913
  • 10
  • 50
  • 116
  • 1
    Usually the database will have an iterator that keeps incrementing, since it is more efficient to just assign the next one over looking for a "gap". – Willem Van Onsem Jun 29 '19 at 14:33
  • 1
    Related: https://stackoverflow.com/q/16582704/67579 – Willem Van Onsem Jun 29 '19 at 14:35
  • @WillemVanOnsem then it is better to create a new field as a serial number ?? Also, is there is such a built-in field in Django like (SerialnumberField) or something related? – Ahmed Wagdi Jun 29 '19 at 14:38

1 Answers1

0

I did it manually by looping over items and find a gap to fill :

                check_for_gap = BuyInvoice.objects.all()
                number = 1
                for item in check_for_gap:
                    if item.id != number:
                        new_invoice = BuyInvoice.objects.create(user=user, branch=branch, supplier=supplier_obj, id=number)
                        return redirect('invoice_buy_details', pk=new_invoice.id)
                    else:
                        number += 1
Ahmed Wagdi
  • 3,913
  • 10
  • 50
  • 116
  • 3
    Imagine you have 50,000 records. the performance is going to get down. let me ask why you want to do it? engine database use automatic ID to help us and control the insert and rollback. may there is another way to get what you want – Bob White Jun 29 '19 at 14:56
  • @BobWhite I'm using this id's as serial number for printable invoices, so I needed it to be in orderer without gaps! And yes your point of view accurate, with bigger data the performance will be sick !! didn't find any other solutions till now. – Ahmed Wagdi Jun 29 '19 at 16:44
  • 1
    you should use a field number and manually increse up it. but dont touch primary as seria number for invoice. – Bob White Jun 30 '19 at 17:13