Robin  van Leeuwen
Robin van Leeuwen

Reputation: 2711

SQLALchemy access column objects

I'm trying to find my way around SQLAlchemy. And i'm trying to find out how i can access the Column objects through a table instance.

I currently have my application written with Peewee as ORM and there i can do the following:

In [15]:from db.models.vehicle import Vehicle
In [16]: Vehicle.code
Out[16]: <db.fields.RsCharField at 0x7fd93e53e780>
In [17]: Vehicle.code.default
Out[17]: ''

or through an actual instance:

In [10]: a = Vehicle()
In [11]: a._meta.fields["code"]
Out[11]: <db.fields.RsCharField at 0x7f08ce49da90>

When i do the same in SQLAlchemy , i get an:

In [11]: Vehicle.code
Out[11]: <sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7fd9105f2938>

But i want to have the actual Column type, since i extended the Column type to have extra attributes i want to access:

class RsColumn(Column):

    def __init__(self, *args, ui_group=None, ui_sequence=None, **kwargs):
        self.ui_group = ui_group
        self.ui_sequence = ui_sequence
        super().__init__(*args, **kwargs)

(So in this case i want to access the RsColumn objects, that i use in my Table declaration)

Upvotes: 2

Views: 5495

Answers (2)

Ameet S M
Ameet S M

Reputation: 190

Adding to the Sergey's Answer, accessing the relationship attributes in a table class returns the InstrumentedAttribute.

For accessing the columns of the child tables from parent table.

for example,

class Bbc(Base):
    name = Column(String)
    ...
    code_policy = relationship('CodePolicy') # related via foreign key
class CodePolicy(Base):
    policy_description = Column(String)

If you want to access the columns in the CodePolicy table from Bbc table via the code_policy relationship, then

Bbc.code_policy.property.table.c.policy_description

Upvotes: 0

Sergey Gornostaev
Sergey Gornostaev

Reputation: 7807

Vehicle.__table__.c.code.type

You can read about it in SQLAlchemy Documentation: Accessing Tables and Columns

Upvotes: 4

Related Questions