1

I need to generate a DB Model from an array of strings like this:

strings = ['String 1', 'String 2', ..., 'String N-1', 'String N']

I need a table in my DB with this shape

ORIGIN | STRING 1 | STRING 2 |...| STRING N
 char  |   char   |   char   |...| char

I created my Model Class like this:

class FixedCharField(models.Field):
  def __init__(self, max_length, *args, **kwargs):
    self.max_length = max_length
    super(FixedCharField, self).__init__(max_length=max_length, *args, **kwargs)

  def db_type(self):
    return 'char(%s)' % self.max_length


class MyModel(models.Model):
    strings = get_my_array() # aux function to generate the array
    origin = FixedCharField(max_length=3)
    for string in strings:
        string = FixedCharField(max_length=3)

As you can see, I need each column name to have a fixed size of 3, so I used the custom FixedCharField that I found in this link Fixed Char Field

My question is, will this work? And this is the correct approach to do this?

2
  • 1
    This will not work sinc it will each time overwrite the item variable, hence you end up with only the last one. Commented Feb 10, 2020 at 19:15
  • hmm that's true. Commented Feb 10, 2020 at 19:18

1 Answer 1

3

This will not work since here your are each time overwriting the item variable, until it gets overwritten for the last time. That will then be the item that Django will "see" after the class is initialized.

You can update the locals() dictionary in the class for this:

class MyModel(models.Model):
    strings = get_my_array()
    for string in strings:
        locals()[string] = FixedCharField(max_length=3)

But still it looks very ugly. It might be better here to contribute your elements to the model:

class MyModel(models.Model):
    # other fields
    pass

for string in get_my_array():
    FixedCharField(max_length=3).contribute_to_class(MyModel, string)
Sign up to request clarification or add additional context in comments.

2 Comments

Better yet, though, for code completion, etc., might be to just write a script that generates regular foo = FixedCharField(...) statements and paste those in.
Ohhh that's the correct approach, I see! Thank you. I updated the name of arrays to make more sense, if you want to also update your answer would be helpful to anyone who look for this in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.