Skip to content

MachineMixin fails in Django migrations with historical models #551

@atinary-bvollmer

Description

@atinary-bvollmer

Description

When using MachineMixin with Django models, data migrations that use apps.get_model() fail because Django's historical models don't inherit class attributes like state_machine_name.

Error

ValueError: None is not a valid state machine name.

How to Reproduce

  1. Create a Django model with MachineMixin:
from statemachine.mixins import MachineMixin

class MyModel(models.Model, MachineMixin):
    state_machine_name = "myapp.MyStateMachine"
    status = models.CharField(max_length=20)
  1. Create a data migration using RunPython:
def backfill_data(apps, schema_editor):
    MyModel = apps.get_model("myapp", "MyModel")
    for obj in MyModel.objects.all():  # Fails here
        obj.some_field = "value"
        obj.save()

class Migration(migrations.Migration):
    operations = [
        migrations.RunPython(backfill_data),
    ]
  1. Run python manage.py migrate

Suspected Cause

Django's apps.get_model() returns a dynamically created "historical" model class that doesn't include mixin class attributes. When MachineMixin.__init__ runs, self.state_machine_name is None, triggering the error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions