0

I need a custom alphanumeric sequence for a custom_id on django model for each Product.

def save(self, *args, **kwargs):
    if self.custom_id is None:
        self.custom_id = f"{custom_seq(self.id)}"
    return super(Product, self).save(*args, **kwargs)

I want custom Alphanumeric sequence to be generated as:

eg. letters=4, digits=3 then,
'AAAA001', 'AAAA002', 'AAAA003'... 'ZZZZ999'
if letters =3 and digits =4
'AAA0001', 'AAA0002'... 'ZZZ9999'

Here is my try:

def custom_seq(pk, letter=4, digits=3):
  init = ''
  alpha = string.ascii_uppercase
  for i in alpha:
    for j in alpha:
      for k in alpha:
         for l in alpha: 
            yield(i+j+k+l) 

This will genrate only 'AAAA' to 'ZZZZ', but not sure how to add digits in front of it and make this dynamic.

trex
  • 3,848
  • 4
  • 31
  • 54
  • What do you mean by "make this dynamic"? And the `itertools` has a function, `product`, which might be of help. – Scott Hunter Aug 31 '20 at 02:43
  • @ScottHunter - Thanks, let me check `product`, Dynamic means- in my code you might have observed I have written 4 for looks when letters are 4. Those 4 loops should dynamic, so that if I change the `letters` to some other `number` say 3 or 5 for loops should change for that number of times. – trex Aug 31 '20 at 02:46
  • what do you want the `self.id` to do when you passed it to `custom_seq` ? Seems like you want a custom generator to yield `AAA001` ... , but how do you want to control where does the sequence start from? Like do you want to control whether first sequence is `AAA001` or `AAA999`? – fusion Aug 31 '20 at 02:48
  • @fusion - please ignore, I was planning to initialize with id `itself` instead of digits but the problem was it could have any number of digits such as 2 digits 3 digits etc. which would vary my sequence length – trex Aug 31 '20 at 02:50
  • Are you perhaps looking for something like this? https://stackoverflow.com/a/2030081/1294308 – rriehle Aug 31 '20 at 02:52
  • @rriehle - Thanks but Random string would not help. – trex Aug 31 '20 at 02:55

1 Answers1

3

You can use itertools.product in order to get the combinations of alphabets and digits easily.

import string
import itertools

def custom_seq(pk, letter=4, digits=3):
    alpha = string.ascii_uppercase
    digit = string.digits
    alpha_list = [alpha]*letter
    digit_list = [digit]*digits
    for i in itertools.product(*alpha_list):
        for j in itertools.product(*digit_list):
            yield "".join(i + j)
            # print("".join(i + j))
Ahmed Mamdouh
  • 696
  • 5
  • 12