简体   繁体   English

Django - 使用for循环从列表创建模型字段

[英]Django - Creating model fields from list with for loop

I have a long list of 100 labels I need my model to have as fields and to also call in succession to access them in other parts of code. 我有100个标签的长列表,我需要我的模型作为字段,并且还连续调用以在代码的其他部分访问它们。 I am going to need to modify them in the future so I would like to be able to do it in one place. 我将来需要修改它们,所以我希望能够在一个地方完成它。 Is there a simple way to do this. 有一个简单的方法来做到这一点。 For example: 例如:

labels = ['height', 'weight', 'age']

In models.py 在models.py中

class MyModel(models.Model):
    for label in labels:
        label = models.CharField(max_length=255)

Would the above be equal to : 以上是否等于:

class MyModel(models.Model):
    height = models.CharField(max_length=255)
    weight = models.CharField(max_length=255)
    age = models.CharField(max_length=255)

Django models have an add_to_class method which adds a field (or any attribute, really) to a class. Django模型有一个add_to_class方法,它可以向一个类添加一个字段(或任何属性)。 The syntax is MyModel.add_to_class(name, value) . 语法是MyModel.add_to_class(name, value) The resulting code would be: 结果代码将是:

class MyModel(models.Model):
    pass

for label in labels:
    MyModel.add_to_class(label, models.CharField(max_length=255))

Internally, this will call the contribute_to_class method on the value passed, if that method exists. 在内部,如果该方法存在,这将对传递的值调用contribute_to_class方法。 Static attributes are added to the class as-is, but fields have this method and all subsequent processing will ensue. 静态属性按原样添加到类中,但是字段具有此方法,并且随后将进行所有后续处理。

Using locals() should work here: 使用locals()应该在这里工作:

class MyModel(models.Model):
    for label in labels:
        locals()[label] = models.CharField(max_length=255)

    del locals()['label']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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