[Python] How to migrate Enumfield values in Django properly?

Discussão em 'Python' iniciado por Stack, Julho 8, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose we have an Enum:

    class MyEnum(Enum):
    FOO = "FOO"
    BAR = "BAR"
    BAZ = "BAZ"


    that is used in a field:

    from enumfields import EnumField

    class FooModel (models.Model)
    foo_field = EnumField(
    MyEnum, null=True, blank=True, default=MyEnum.FOO)


    Then I want to remove one of the fields in MyEnum, because I do not want value FOO in my database anymore

    class MyEnum(Enum):
    BAR = "BAR"
    BAZ = "BAZ"


    from enumfields import EnumField

    class FooModel (models.Model)
    foo_field = EnumField(
    MyEnum, null=True, blank=True, default=MyEnum.BAR)


    I need to migrate data, so my migration may look like this:

    def migrate_not_for_sale_to_private(apps, schema_editor):
    FooModel = apps.get_model("foo", "FooModel")
    for obj in FooModel.objects.all():
    if obj.foo_field == "FOO":
    obj.foo_field = "BAR"
    obj.save()


    This one fails, because I changed allowed values for foo_field to BAR and BAZ, and so if obj has value FOO, it blows up with not allowed value error.

    How one should do it properly? I could leave MyEnum values as they are, marking one as legacy, but in a long run it leads to a lot of potential legacy fields. The other way could be running raw SQL command (assume I am using PostgreSQL).

    Continue reading...

Compartilhe esta Página