Shraft
Shraft

Reputation: 332

Why use "db.*" in SqlAlchemy?

I am working on a project using Flask and SqlAlchemy. Me and my colleagues found two ways to define a table. Both work, but what is the different?

Possibility I

base = declarative_base()

class Story(base):
        __tablename__ = 'stories'
        user_id = Column(Integer, primary_key=True) 
        email = Column(String(100), unique=True)
        password = Column(String(100), unique=True)

Possibility II

db = SQLAlchemy()

class Story(db.Model):
        __tablename__ = 'stories'
        user_id = db.Column(Integer, primary_key=True) 
        email = db.Column(String(100), unique=True)
        password = db.Column(String(100), unique=True)

We want to choose one option, but which one? It is obvious that both classes inherit from a different parent class, but for what are these two possibilities used for?

Upvotes: 2

Views: 56

Answers (1)

ljmc
ljmc

Reputation: 5294

Possibility 1 is raw SQLAlchemy declarative mapping.

Possibility 2 is Flask-SQLAlchemy.

Both map a class to SQL table (or something more exotic in SQL) in a declarative style, i.e. the class is mapped to an automatically generated table.

Choosing which one to use however is a matter of opinion.

I'll say that using Flask-SQLAlchemy is obviously locking the application to Flask, but that's basically a non-problem since switching frameworks is very uncommon.

NB. __tablename__ is optional with Flask-SQLAlchemy.

Upvotes: 2

Related Questions