Search code examples
pythonsqlalchemy

sqlalchemy Move mixin columns to end


I have a sqlalchemy model, where all most all tables/objects have a notes field. So to try follow the DRY principle, I moved the field to a mixin class.

class NotesMixin(object):
    notes = sa.Column(sa.String(4000) , nullable=False, default='')

class Service(Base, NotesMixin):
    __tablename__ =  "service"
    service_id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String(255), nullable=False, index=True, unique=True)


class Datacenter(Base, NotesMixin):
    __tablename__ =  "datacenter"
    datacenter_id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String(255), nullable=False, index=True, unique=True)


class Network(Base, NotesMixin, StatusMixin):
    __tablename__ =  "network"
    network_id = sa.Column(sa.Integer, primary_key=True)

etc...

Now the notes column is the first column in the model/db. I know it does not affect the functionality of my app, but it irritates me a bit to see notes before id, etc. Any way to move it to the end?


Solution

  • I'm late to this question but for reference, if you use SA 2.0, just pass sort_order to mapped_column, for example:

    class NotesMixin:
        note = mapped_column(String(255), sort_order=999)
    

    https://docs.sqlalchemy.org/en/20/changelog/whatsnew_20.html#orm-declarative-applies-column-orders-differently-control-behavior-using-sort-order