3

It just works when I simply do an inheritance with my class

class User(Base):
    __tablename__ = ’users’
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

And then i'm able to create the table using Base.metadata.create_all(engine)

My question is, how can sqlalchemy know that i have already defined User (inherited from Base) ?

Determinant
  • 3,886
  • 7
  • 31
  • 47
  • 1
    Because one is able to iterate over all sub-classes of the class (in this case `Base`). In fact, the answer is in the question asked just 2 days ago: [How to iterate through every class declaration, descended from a particular base class?][http://stackoverflow.com/a/8957113/99594] – van Jan 24 '12 at 16:14

2 Answers2

5

Each declarative base class maintains the registry of descended classes, which is filled when class definition is executed (in __init__() method of metaclass). But this registry is not actually used by create_all(). The MetaData instance (Base.metadata) is a part of SQLAlchemy core (not ORM) and is responsible for maintaining the registry of tables. MetaData instance remembers the table when it is created (and stored in __table__ attribute of class) from the same __init__() method of declarative metaclass. You can get this list of tables through Base.metadata.sorted_tables property.

Denis Otkidach
  • 32,032
  • 8
  • 79
  • 100
3

When you inherited from any class it will give you chain to trace over all its sub classes. With the help of trick given in How to iterate through every class declaration, descended from a particular base class? you will get all sub classes.

Hope this will help you to solve your problem.

Community
  • 1
  • 1
Nilesh
  • 20,521
  • 16
  • 92
  • 148
  • 1
    I have another question related to this: how is the attribute `__table__` of user-defined class (which inherits from declarative Base) specifically made according to the content of that defined class? – Determinant Jan 25 '12 at 04:26
  • 1
    I check the coding and found that they are set on the bases of the __tablename__ attribute. Yoc can check the codding in http://src.chromium.org/svn/trunk/tools/build/third_party/sqlalchemy_0_7_1/sqlalchemy/ext/declarative.py and check the function `def _as_declarative`. – Nilesh Jan 25 '12 at 07:56