新项目检查丢失的ID并创建它

时间:2019-06-29 14:30:39

标签: python django database

有没有一种方法可以让Django检查缺少的ID号并在此插槽中创建一个新项目,而不是使用新ID进行创建。

这是尝试做的事情

我有模型

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)

每当我向其中添加新项目时,它都会将自动生成的ID设为1、2、3、4、5

现在,如果我删除了ID为3的项目,那么我尝试创建新项目,我希望将其添加到3的ID中,而不是6

1 个答案:

答案 0 :(得分:0)

我通过遍历项目并找到空白来手动完成:

                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