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

19 visningar
Hoppa till det första olästa meddelandet

mkmo...@gmail.com

oläst,
28 jan. 2022 18:14:342022-01-28
till 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
Svara alla
Svara författaren
Vidarebefordra
0 nya meddelanden