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) ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With