我正在尝试动态访问我使用SQL Alchemy创建的表的列列表。我创建了这样的表:
base.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
import os
# Create database engine
db_name = 'database.db'
db_path = os.path.join(os.path.dirname(__file__), db_name)
db_uri = 'sqlite:///{}'.format(db_path)
engine = create_engine(db_uri, convert_unicode=True)
# Declarative base model to create database tables and classes
Base = declarative_base()
Base.metadata.bind = engine # Bind engine to metadata of the base class
# Create database session object
db_session = scoped_session(sessionmaker(bind=engine, expire_on_commit=False))
Base.query = db_session.query_property() # Used by graphql to execute queries
model_planet.py
from .base import Base
from .model_people import ModelPeople
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
class ModelPlanet(Base):
"""Planet model."""
__tablename__ = 'planet'
id = Column('id', Integer, primary_key=True)
name = Column('name', String, doc="Name of the planet.")
rotation_period = Column('rotation_period', String, doc="Rotation period of the planet.")
orbital_period = Column('orbital_period', String, doc="Orbital period of the planet.")
diameter = Column('diameter', String, doc="Diameter of the planet.")
climate = Column('climate', String, doc="Climate period of the planet.")
gravity = Column('gravity', String, doc="Gravity of the planet.")
terrain = Column('terrain', String, doc="Terrain of the planet.")
surface_water = Column('surface_water', String, doc="Surface water of the planet.")
population = Column('population', String, doc="Population of the planet.")
created = Column('created', String, doc="Record created date.")
edited = Column('edited', String, doc="Record last updated date.")
url = Column('url', String, doc="URL of the planet in the Star Wars API.")
peopleList = relationship(ModelPeople, backref='planet')
在另一个文件中,我正在导入model_planet.ModelPlanet
并尝试按照此处的文档访问其列:http://docs.sqlalchemy.org/en/latest/core/metadata.html
from database.model_planet import ModelPlanet
print(type(ModelPlanet))
for column in ModelPlanet.columns:
print(column)
我得到以下内容:
<class 'sqlalchemy.ext.declarative.api.DeclarativeMeta'>
Traceback (most recent call last):
[...]
for column in ModelPlanet.columns:
AttributeError: type object 'ModelPlanet' has no attribute 'columns'
我想这与我定义表格的方式有关。我怎样才能动态访问其列?
由于
答案 0 :(得分:3)
您需要获得以下访问权限:
for column in ModelPlanet.__table__.columns:
print(column)