trex
trex

Reputation: 4057

Django auto increment to custom field

I have Product db model, which should generate a code every time a new Product has been added.

class Product(models.Model): # Common
  code = models.CharField(_("Product Code"), blank=True, max_length=100)
  #... Other Fields 

  def __str__(self):
      return self.code

  def custom_seq(pk, letters=4, digits=3):
     """
     Generates a sequence when letters=4, digits=3 then, 'AAAA000', 'AAAA001', ..., 'ZZZZ999'
     Generates a sequence when letters=3, digits=4 then, 'AAA0000', 'AAA0001',..., 'ZZZ9999'
     """
      alpha_list = [string.ascii_uppercase]*letters
      digit_list = [string.digits]*digits
      for i in itertools.product(*alpha_list):
        for j in itertools.product(*digit_list):
          yield "".join(i + j)

  def save(self, *args, **kwargs):
    product_code = next(self.custom_seq())
    print("Code", product_code) #-- prints `AAAA000`
    if not self.code:
        self.code = product_code
    return super(Product, self).save(*args, **kwargs)

Everytime, I save a new product its generating only first sequence of my custom_seq() ie. AAAA000. but it should add new code to each newly generated instance such as 'AAAA001', 'AAAA002', 'AAAA003'...

Upvotes: 0

Views: 331

Answers (1)

Laxmikant Ratnaparkhi
Laxmikant Ratnaparkhi

Reputation: 5023

You are instantiating custom_seq generator each time you'are creating a new instance.

Put your custom_seq(pk, letters=4, digits=3) method somewhere outside your Product model (I would recommend you to put separately in Utility module) and instantiate it globally.

Finally, use it inside your save method.

seq  = custom_seq()

class Product(models.Model): # Common
  code = models.CharField(_("Product Code"), blank=True, max_length=100)
  #... Other Fields 
  #... Other methods

def save(self, *args, **kwargs):
  if not self.code:
    self.code = next(seq)
  return super(Product, self).save(*args, **kwargs)

Upvotes: 1

Related Questions