循环遍历Django模型类中的字段

时间:2015-04-22 00:34:36

标签: django django-models

我试图消除models.py文件中的重复代码,但是以下循环不起作用并返回" OperationalError没有这样的列my_app.rank。"

from django.db import models

rank_fields = [
    'E1', 'E2','E3', 'E4', 'E5', 'E6', 'E7', 'E8', 'E9',
    'W1', 'W2', 'W3', 'W4', 'W5', 'O1E', 'O2E', 'O3E', 'O1',
    'O2', 'O3', 'O4', 'O5', 'O6', 'O7', 'O8', 'O9', 'O10'
]

class withDependents(models.Model):
    MHA = models.CharField(max_length = 5)
    for rank in rank_fields:
        rank = models.DecimalField(max_digits = 10, decimal_places = 2)

编辑:

我发现了一种可行的解决方案:

# add rank fields to withDependents and withOutDependents
rank_fields = [
    'E1', 'E2','E3', 'E4', 'E5', 'E6', 'E7', 'E8', 'E9',
    'W1', 'W2', 'W3', 'W4', 'W5', 'O1E', 'O2E', 'O3E', 'O1',
    'O2', 'O3', 'O4', 'O5', 'O6', 'O7', 'O8', 'O9', 'O10'
    ]

for rank in rank_fields:
        withDependents.add_to_class(rank, models.DecimalField(max_digits = 10, decimal_places = 2))
        withOutDependents.add_to_class(rank, models.DecimalField(max_digits = 10, decimal_places = 2))

0 个答案:

没有答案