【问题标题】:Django model dynamic choices migrationDjango 模型动态选择迁移
【发布时间】:2019-08-18 18:30:36
【问题描述】:

我有一个具有动态选择的模型字符域

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 时,它会为包含所有选项的字段生成迁移。

如果没有如此巨大的迁移,我该如何解决这个问题。每次运行 makemigrations 时手动删除此迁移是一件很痛苦的事情。

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

【问题讨论】:

    标签: django


    【解决方案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)
    

    我同意这个解决方案有点老套,但它确实有效。

    【讨论】:

    • 感谢您的提示,我正在考虑相同的方法,但希望在 django 中有一个适当的迁移操作标志,无论如何这看起来是迄今为止最好的工作。
    猜你喜欢
    • 2021-10-26
    • 2018-02-20
    • 2017-11-18
    • 2012-11-23
    • 2015-01-22
    • 1970-01-01
    • 2017-05-14
    • 2011-08-25
    • 1970-01-01
    相关资源
    最近更新 更多