Setting up indexes in __table_args__ that depend on columns created in __declare_first__

26 views
Skip to first unread message

Randy Syring

unread,
Dec 14, 2021, 4:32:33 PM12/14/21
to sqlalchemy
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.

Mike Bayer

unread,
Dec 14, 2021, 5:10:36 PM12/14/21
to noreply-spamdigest via sqlalchemy
Hi Randy!

inside of __declare_first__() the table is ready, you can just set it up

def __declare_first__(cls):
    Index("my_idx", cls.__table__.c.colname)

have a great holiday season!

- mike
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
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+...@googlegroups.com.

Reply all
Reply to author
Forward
0 new messages