how can each user get increment and unique id on same table in django

Viewed 209

Each time i want to add an invoice, i want to have a unique invoice_id which is an increment number (+1), but the problem is that i have a multiple users app, so i get the error that this invoice_id already exist. how can i customize the ids so each user can have its ids following the latest of same user.

class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=64)

class Invoice(models.Model):
company = models.ForeignKey('Company', on_delete=models.CASCADE)
invoice_id = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=256)
1 Answers

add an last_invoice field in your company record. Then let it do the work for you by adding a function that generates new invoice:

class Company(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=64)
    last_invoice = models.CharField(max_length=20)

    def get_invoice(self):
        l_newNum = self.last_invoice + '1' #your number here 
        self.last_invoice = l_newNum
        self.save()
        return l_newNum

class Invoice(models.Model):
    company = models.ForeignKey('Company', on_delete=models.CASCADE)
    #you no longer need unique as it will create a mess between companies
    invoice_id = models.CharField(max_length=20)
    name = models.CharField(max_length=256)

    def save(self):
        self.invoice_id = self.company.get_invoice()
        super(Invoice,self).save()

You need to fill in the details here and there, but this should work for you. IDeally I would suggest that the get_invoice is actually used to automatically create Invoice entry for the company, but this would depend on the concrete case you are building.

Related