Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Sqlalchemy, what's different in defining table using Base and Table

Tags:

I know i can define a table using Table:

user = Table('user', metadata,
    Column('user_id', Integer, primary_key = True),
)

and using Base:

Base = declarative_base()    
class User(Base):
        __tablename__ = 'user'
        user_id= Column(Integer, primary_key = True)

but what's the different???

like image 223
CodeBoy Avatar asked Sep 23 '13 15:09

CodeBoy


People also ask

What is a base in SQLAlchemy?

A base class stores a catlog of classes and mapped tables in the Declarative system. This is called as the declarative base class. There will be usually just one instance of this base in a commonly imported module. The declarative_base() function is used to create base class. This function is defined in sqlalchemy.

What does base MetaData Create_all do?

create_all() creates foreign key constraints between tables usually inline with the table definition itself, and for this reason it also generates the tables in order of their dependency.

What is SQLAlchemy table?

The SQL Expression Language constructs its expressions against table columns. SQLAlchemy Column object represents a column in a database table which is in turn represented by a Tableobject. Metadata contains definitions of tables and associated objects such as index, view, triggers, etc.

What is MetaData in SQLAlchemy?

The queries in a relational database are usually created on a Table of a database. These tables are represented as Table objects in Python SQLAlchemy named as Table. The MetaData is an object which consists of Table objects keyed to their string names.


1 Answers

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id = Column('id', Integer, primary_key=True)
    name = Column('name', Unicode(64))

is just syntactic sugar for

metadata = MetaData()

user = Table('user', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', Unicode(64)),
)

class User(object):
    pass

mapper(User, user)  # this will modify the User class!
like image 125
pi. Avatar answered Sep 22 '22 21:09

pi.