Search code examples
pythonmigrationalembicormar

Alembic autogenerate doesn't detect column detect on parent class (Alembic + Ormar ORM)


Here what I want to achieve, I want models common fields inside a base model namely BaseModel as pictured below.

Mixins

class TimeStampMixin:
    created: datetime.datetime = ormar.DateTime(default=datetime.datetime.now)
    updated: datetime.datetime = ormar.DateTime(default=datetime.datetime.now)


class IdMixin:
    id: uuid.UUID = ormar.UUID(default=uuid.uuid4, primary_key=True)

Base Model

class BaseModel(ormar.Model, IdMixin, TimeStampMixin):
   ...

Concrete classes

class Concrete(BaseModel):
   class Meta(BaseMeta)

what I expect is to have all id, created, updated added to the auto-generated migration, but below is the output of alembic revision --autogenerate

Alembic output

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('concretes',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('concretes')
Note: When added directly to Concrete model, all changes are perfectly detected, but I have lots of classes and don't want to repeat myself.

Can somebody help with a link or an explanation on how to achieve this ?


Solution

  • I end-up using abstract model instead of Mixins (https://collerek.github.io/ormar/models/inheritance/). Hopes it helps somebody else.

    class TimeStampMixin(ormar.Model):
        created: datetime.datetime = ormar.DateTime(default=datetime.datetime.now)
        updated: datetime.datetime = ormar.DateTime(default=datetime.datetime.now)
    
        class Meta(ormar.ModelMeta):
           abstract = True
           ...
    
    class IdMixin(ormar.Model):
        id: uuid.UUID = ormar.UUID(default=uuid.uuid4, primary_key=True)
        class Meta(ormar.ModelMeta):
           abstract = True
           ...