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.

6
  • What do you mean by "make this dynamic"? And the itertools has a function, product, which might be of help. Commented Aug 31, 2020 at 2: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. Commented Aug 31, 2020 at 2: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? Commented Aug 31, 2020 at 2: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 Commented Aug 31, 2020 at 2:50
  • Are you perhaps looking for something like this? stackoverflow.com/a/2030081/1294308 Commented Aug 31, 2020 at 2:52

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.