Как выглядит моя миграция: (использует пакетные операции, поскольку база данных разработки является sqlite)
Код: Выделить всё
def upgrade() -> None:
"""Upgrade schema."""
with op.batch_alter_table("authors") as batch_op:
batch_op.create_unique_constraint(
"uq_author_fullname", ["firstname", "lastname"]
)
pass
def downgrade() -> None:
"""Downgrade schema."""
with op.batch_alter_table("authors") as batch_op:
batch_op.drop_constraint("uq_author_fullname", type_="unique")
pass
Код: Выделить всё
CREATE TABLE _alembic_tmp_authors (
id INTEGER NOT NULL,
firstname VARCHAR(100),
lastname VARCHAR(100),
PRIMARY KEY (id),
CONSTRAINT uq_author_fullname UNIQUE (firstname, lastname),
UNIQUE (lastname),
UNIQUE (firstname)
)
Код: Выделить всё
class Author(Base):
__tablename__ = "authors"
id = Column(Integer, primary_key=True)
firstname = Column(String(100))
lastname = Column(String(100))
books = relationship("Book", secondary=authorBook, back_populates="authors")
UniqueConstraint("firstname", "lastname", name="fullname_unique")
Теперь предположим, что два объекта: Питер Паркер и Питер Гриффин
И следующий код вставки:
Код: Выделить всё
# Imports ommited
def add(db: Session, first_name: str, last_name: str):
author = Author(firstname=first_name, lastname=last_name)
db.add(author)
try:
db.commit()
db.refresh(author)
except IntegrityError:
return None
return author
Мобильная версия