jhrs21
jhrs21

Reputation: 391

Instancing a Table from __tablename__ in SQLAlchemy

Is it possible to instance a table with its tablename?

I've looked for in SQLAlchemy documentation and I couldn't find anything.

class A():
    __tablename__ = 'x'

newTable = Table('x')

Is possible something like this?

This is a pseudo-language, not real Python code

Thanks,

Upvotes: 0

Views: 1068

Answers (2)

snakecharmerb
snakecharmerb

Reputation: 55724

Given some model Foo:

class Foo(Base):
    __tablename__ = 'foos'
    ...

the associated table object can be accessed directly via the __table__ attribute (provided that the entity has been mapped, for example via Base.metadata.create_all):

tbl = Foo.__table__

If only the value of Foo.__tablename__ is available the table can be retrieved using reflection:

tbl = sa.Table('foos', sa.MetaData(), autoload_with=engine)

Upvotes: 1

Tanveer Alam
Tanveer Alam

Reputation: 5275

Create_a.py

import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class A(Base):
    __tablename__ = 'X'
    A_id = Column(Integer, primary_key=True)
    A_name = Column(String(250), nullable=False)

engine = create_engine('sqlite:///sqlalchemy_example.db')

Base.metadata.create_all(engine)

Insert_a.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from Create_a import A, Base, engine

Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)

session = DBSession()
print A.__tablename__ 
A.__tablename__ = A
new_A = A.__tablename__(A_name='new A')
session.add(new_A)
session.commit()

Were A.__tablename__ is X

Upvotes: 1

Related Questions