I'm trying to create a mixin that will setup FK columns that are dynamically named based on the name of the parent as opposed to a static name like `parent_id`. If was going to do the latter, I could easily use `declarted_attr` but since I want the former, I thought I could use `__declare_first__()`. It works except that I also need to setup an index on the FK column. When trying to do that with `__table_args__()`, I get an exception b/c, `__table_args__()` gets called before `__declare_first__()`.
class FlawMixin:
@sa.orm.declared_attr
def __tablename__(cls):
return f'{cls.__flaw_ident__}_flaws'
@sa.orm.declared_attr
def __table_args__(cls):
return (
sa.Index(f'ix_{cls.__flaw_ident__}_flaws_{cls.__flaw_ident__}',
f'{cls.__flaw_ident__}_id'),
)
@classmethod
def __declare_first__(cls):
setattr(cls, f'{cls.__flaw_ident__}_id', sa.Column(
sa.Integer,
sa.ForeignKey(cls.__flaw_parent__.id, ondelete='cascade'),
nullable=False
))
setattr(cls, cls.__flaw_ident__,
sa.orm.relationship(cls.__flaw_parent__, lazy='raise_on_sql'))
I realize I have an event ordering issue with the way this is setup. Just not sure what the correct way is to solve it.
Thanks in advance for any help you can provide.