SQLAlchemyは、データベーススキーマを作成するための最も人気のあるライブラリの1つであるとよく言われています。今日は、見積もり検索アプリケーション用の小さなデータスキーマを作成する簡単な例を見ていきます。PostgreSQLをDBMSとして使用します。
私の意見では、マッパーに基づく従来のアプローチよりも単純で明確であるため、モデルを定義するために宣言型アプローチを使用します。まず、ER図をスケッチしましょう。
, , , .
SQLAlchemy . Quote relationship.
from sqlalchemy import Column, ForeignKey, Integer, String, Text, Date, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Topic(Base):
__tablename__ = 'topic'
__tableargs__ = {
'comment': ' '
}
topic_id = Column(
Integer,
nullable=False,
unique=True,
primary_key=True,
autoincrement=True
)
name = Column(String(128), comment=' ')
description = Column(Text, comment=' ')
def __repr__(self):
return f'{self.topic_id} {self.name} {self.description}'
class Author(Base):
__tablename__ = 'author'
__tableargs__ = {
'comment': ' '
}
author_id = Column(
Integer,
nullable=False,
unique=True,
primary_key=True,
autoincrement=True
)
name = Column(String(128), comment=' ')
birth_date = Column(Date, comment=' ')
country = Column(String(128), comment=' ')
def __repr__(self):
return f'{self.author_id} {self.name} {self.birth_date} {self.country}'
class Quote(Base):
__tablename__ = 'quote'
__tableargs__ = {
'comment': ''
}
quote_id = Column(
Integer,
nullable=False,
unique=True,
primary_key=True,
autoincrement=True
)
text = Column(Text, comment=' ')
created_at = Column(DateTime, comment=' ')
author_id = Column(Integer, ForeignKey('author.author_id'), comment=' ')
topic_id = Column(Integer, ForeignKey('topic.topic_id'), comment=' ')
author = relationship('Author', backref='quote_author', lazy='subquery')
topic = relationship('Topic', backref='quote_topic', lazy='subquery')
def __repr__(self):
return f'{self.text} {self.created_at} {self.author_id} {self.topic_id}'
, , . , Base
. , __tablename__
__tableargs__
.
, . , . relationship
. , , . lazy
, . joined
subquery
: , -, , - .
__repr__
, .
データスキーマを作成した後、さまざまな方法でテーブルを展開できます。不整合がないことを確認するには、以前にデータベースを作成した次の行を使用できます(例はpostgresqlの場合です)。
engine = create_engine('postgresql://user:password@host:port/db_name')
Base.metadata.create_all(engine)
ただし、移行を管理するためのツール、たとえばalembicを使用する方がはるかに便利です。実際、データベースをある一貫した状態から別の状態に移動することができます。