Reputation: 4037
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.
Upvotes: 0
Views: 1379
Reputation: 706
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))
Upvotes: 3