Django从数组生成模型字段

问题描述 投票:1回答:1

我需要从这样的字符串数组生成数据库模型:

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

我需要在数据库中使用这种形状的表

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

我这样创建了我的模型类:

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)

如您所见,我需要每个列名的固定大小为3,因此我使用了在此链接Fixed Char Field中找到的自定义FixedCharField。

我的问题是,这行得通吗?这是执行此操作的正确方法吗?

我需要从这样的字符串数组生成数据库模型:strings = ['String 1','String 2',...,'String N-1','String N']我需要一个表在我的DB中具有这种形状STRING 1 | ...

python django
1个回答
2
投票

这将不起作用,因为在这里您每次都覆盖item变量,直到最后一次覆盖它为止。那将是Django在类初始化后将“看到”的项。

© www.soinside.com 2019 - 2024. All rights reserved.