Django模型动态选择迁移

时间:2019-03-28 03:56:19

标签: django

我有一个模型charfield,可以动态选择

DecodingError

我的问题是,当我运行class MachineChoices(object): def get_machine_choices(self): # call external service to get a full list of machines ... def __iter__(self): yield from self.get_machine_choices() class ExceptionMapping(models.Model): machine_id = models.IntegerField(null=True, blank=True, choices=MachineChoices()) 时,它将为具有所有选择的字段生成一个迁移。

如果没有如此巨大的迁移,我该如何解决这个问题。每次运行makemigrations时手动删除此迁移都是一个麻烦。

请注意: 我在问为什么会这样,因为我已经问过before

1 个答案:

答案 0 :(得分:1)

我在迁移方面遇到了问题,我通过执行不同的代码来解决它们,具体取决于当前进程是否与迁移相关,如您在question中所见。

对于您而言,您可以执行以下操作:

class ExceptionMapping(models.Model):
    import sys
    if 'makemigrations' not in sys.argv and 'migrate' not in sys.argv:
        machine_id = models.IntegerField(null=True, blank=True, choices=MachineChoices())
    else:
        machine_id = models.IntegerField(null=True, blank=True)

我同意这种解决方案有点笨拙,但是可以。