Stop Django from creating migrations if the list of choices of a field changes

前端 未结 2 1606
南笙
南笙 2021-02-12 17:29

I have a django core app called \"foocore\".

There are several optional pluging-like apps. For example \"superfoo\".

In my case every plugin adds a new choice in

2条回答
  •  清酒与你
    2021-02-12 17:52

    I had a similar problem with a custom field that I made for a Django 1.6 project that had the same general structure. I came to the following solution which works alright:

    class ActivePluginMeta(ModelBase):
        def __new__(cls, name, bases, attrs):
            # Override choices attr
            cls = models.base.ModelBase.__new__(cls, name, bases, attrs)
            setattr(cls._meta.get_field('plugin_name'), 'choices', cls.plugin_name_choices)
            return cls
    
    class ActivePlugin(models.Model, metaclass=ActivePluginMeta):
        plugin_name_choices = get_active_plugins()
        plugin_name = models.CharField(max_length=32, choices=[])
    

    That is for python 3, for python 2 you have to specify the metaclass as follows:

    class ActivePlugin(models.Model):
        __metaclass__ = ActivePluginMeta
    
        plugin_name_choices = get_active_plugins()
        plugin_name = models.CharField(max_length=32, choices=[])
    

提交回复
热议问题