get classes with tablename associated sqlalchemy

时间:2016-11-09 10:41:31

标签: python sqlalchemy declarative tablename

I have a file EE_log_declarative.py with all the classes declared, generated by sqlacodegen engine --outfile declarative_model.py, that looks like the below, which imports as well all the data types as classes, like BigInteger, Boolean, ForeignKey, String,...

from sqlalchemy import BigInteger, Boolean, ForeignKey, String

Base = declarative_base()
metadata = Base.metadata

class DataProvider(Base):
    __tablename__ = 'data_provider'
    ...

class DatePattern(Base):
    __tablename__ = 'date_pattern'
    ...

My question is: how do i get only the classes that have a table name associated?

To get the class object in one class definition, currently I'm doing, and it works:

EE_log_declarative.Base.metadata.bind = engine
DBSession = sessionmaker()
DBSession.bind = engine
session = DBSession()

data_provider_account_object =session.query(EE_log_declarative.DataProvider).all()
date_pattern_object = session.query(EE_log_declarative.DatePattern).all()

The idea is to get the class objects dynamically, as many classes as the declarative will have, but only build the class objects that have a table name.

for x in dir(EE_log_declarative):
        attributes = getattr(EE_log_declarative, x)
        is_class = isclass(attributes)
        if is_class:
            try:
                object = session.query(EE_log_declarative, x).all()
                all_class.append(object)
            except:
                pass

basically, in the latest function I want to append only the class objects that have a table name associated, but it's not really working as x are passed as a string.

0 个答案:

没有答案