简体   繁体   中英

Django generate Model Fields from an Array

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?

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:
         = 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)MyModel, string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM