N
N
nurzhannogerbek2017-04-03 19:25:51
Django
nurzhannogerbek, 2017-04-03 19:25:51

Algorithm for generating letters from the Latin alphabet?

Hello!
There is a data model called "Function" . The Function model has a "symbol" field .
When creating a new object, that is, a new record, the user enters the name (the "name" field) of the function through the model window, and the "symbol" field must be generated, or rather, the value must be automatically created in ascending Latin letters and whether such a symbol already exists.
Below, for clarity, you can surprise an example of what exactly should happen. At the moment, I only managed to do from A to Z and check if there is a function with such a symbol, but I can’t figure out how to get subsequent values. Help build an algorithm.
For example:

A
B
-
Z
AA
AB
-
AZ
BA
BB
-
BZ
-
ZZ
AAA
AAB
и так далее

models.py:
class Function(models.Model):
    id= models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    name = models.CharField(max_length=250)
    symbol = models.TextField ()

    def __str__(self):
        return self.name

views.py:
if form.is_valid():
   for i in string.ascii_uppercase:  # (A-Z)
         if not Function.objects.filter(symbol=i, project=project_code).exists():
             function = form.save(commit=False)
             function.symbol = i
             function.save()
             break

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Shirshov Alexander, 2017-04-03
@Keanor

Write the translation from the decimal system (is there any autoincrement?) To 26-decimal, from the required characters.

E
epolyak, 2017-04-04
@epolyak

It is best to store the last value of symbol somewhere separately and update it when writing a new value to the next function.
I didn't check the code, but the idea is the following:

class SymbolCode(models.Model):
    last_code = models.charfield(max....)

# у себя где то в коде
if form.is_valid():
    last_code = SymbolCode.objects.get(pk=1)
    code = last_code ... #как то обновляете код
    last_code.last_code = code
    last_code.save()
    ....
    function.symbol = code
    ....

How to generate code:
code = ""
strs = string.ascii_uppercase
l = len(strs)

for i in range(1, 100):
    ll = len(code)
    if ll == l:
        ll = 0
    elif ll > l:
        ll = ll // l
    code += strs[ll]
    print(code)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question