How to derive table/table name from a column.label()'d object?

20 views
Skip to first unread message

mkmo...@gmail.com

unread,
Jan 28, 2022, 6:14:34 PM1/28/22
to sqlalchemy
In sqlalchemy Core, I can get the table and table name from a regular column by calling `c.table.name`:

    from sqlalchemy import table, column

    t = table('foo', column('bar'))

    assert hasattr(t.c.bar, 'table')
    print(t.c.bar.table.name)

However, If I label a column, the label no longer has a `table` attribute:

    lab = t.c.bar.label('baz')
   
    assert not hasattr(lab, 'table')

Is there any way to go from the label to the column, or from the label to the table?

I've found this one, but it seems a bit clunky:

    lab = t.c.bar.label('baz')

    c = list(lab.base_columns)[0]

    print(c.table.name)

Will label.base_columns always return a set of at least 1 item, or do I need to check?

When will label.base_columns return more than 1 item?

If I wanted something generic that handles both columns and labels, will this work safely:

    def get_table_name(column):
        return list(column.base_columns)[0].table.name

    assert get_table_name(t.c.bar) == 'foo'
    assert get_table_name(t.c.bar.label('baz')) == 'foo'

Thanks and best regards,

Matthew
Reply all
Reply to author
Forward
0 new messages