Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a single table using SqlAlchemy declarative_base

To create the User table I have to use drop_all and then create_all methods. But these two functions re-initiate an entire database. I wonder if there is a way to create the User table without erasing (or dropping) any existing tables in a database?

import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()


class User(Base):
    __tablename__ = 'users'
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    name = sqlalchemy.Column(sqlalchemy.String)

    def __init__(self, code=None, *args, **kwargs):
        self.name = name


url = 'postgresql+psycopg2://user:[email protected]/my_db'
engine = sqlalchemy.create_engine(url)
session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker())
session.configure(bind=engine, autoflush=False, expire_on_commit=False)

Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
like image 842
alphanumeric Avatar asked Jul 22 '17 22:07

alphanumeric


People also ask

How do you create a Table using SQLAlchemy in Flask?

Step 1 - Install the Flask-SQLAlchemy extension. Step 2 - You need to import the SQLAlchemy class from this module. Step 3 - Now create a Flask application object and set the URI for the database to use. Step 4 - then use the application object as a parameter to create an object of class SQLAlchemy.

What is declarative_base in SQLAlchemy?

The declarative_base() base class contains a MetaData object where newly defined Table objects are collected. This object is intended to be accessed directly for MetaData -specific operations. Such as, to issue CREATE statements for all tables: engine = create_engine('sqlite://') Base.

Can you create a database with SQLAlchemy?

Creating and Inserting Data into TablesBy passing the database which is not present, to the engine then sqlalchemy automatically creates a new database.

How do I create a schema in SQLAlchemy?

You can also import the method as such: from sqlalchemy. schema import CreateSchema . And use it directly with engine. execute(CreateSchema(schema_name)) .


1 Answers

You can create/drop individual tables:

User.__table__.drop(engine)
User.__table__.create(engine)
like image 108
univerio Avatar answered Oct 08 '22 04:10

univerio