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.

-- 
SQLAlchemy - 
The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sqlalchemy/45921724-ba6a-40e5-8ae9-cad92169ddfbn%40googlegroups.com.

Reply via email to