Alembic - SQLAlchemy 初始迁移

13

我遇到了一个问题,我无法创建一个初始迁移(Migration),该迁移会自动创建我在models.py中通过使用共享的Base(declarative_base)定义的表格。

当我输入以下命令时:

alembic revision --autogenerate

alembic创建了一个空文件。

我的配置或方法有什么问题吗?

project.base.py:

from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()

env.py:

import sys
import os

sys.path.append(os.path.abspath(os.getcwd()))
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig

from project.base import Base
target_metadata = Base.metadata
def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    engine = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix='sqlalchemy.',
        poolclass=pool.NullPool)

    connection = engine.connect()
    context.configure(
        connection=connection,
        target_metadata=target_metadata
    )

    # target_metadata.reflect(engine, only=[
    #     "django_migrations",
    #     "auth_group_permissions",
    #     "django_session",
    #     "auth_user_user_permissions",
    #     "auth_user_groups",
    #     "django_admin_log",
    #     "auth_permission",
    #     "auth_user",
    #     "sysdiagrams",
    #     "django_content_type",
    #     "auth_group",
    #     "sysdiagrams",
    # ])

    try:
        with context.begin_transaction():
            context.run_migrations()
    finally:
        connection.close()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

示例模型:

# -*- coding: utf-8 -*-

from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, SmallInteger
from sqlalchemy.orm import relationship, backref
from project.base import Base


__schema__ = "Users"


class User(Base):
    __tablename__ = "User"
    __table_args__ = {'schema': __schema__}

    USER_CUSTOMER = 0
    USER_EMPLOYEE = 5
    USER_ADMIN = 10

    USER_TYPES = (
        (USER_CUSTOMER, u'Klient'),
        (USER_EMPLOYEE, u'Obsługa sklepu'),
        (USER_ADMIN, u'Administrator')
    )

    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    email = Column(String(255))
    password = Column(String)
    date_created = Column(DateTime)
    date_updated = Column(DateTime)
    user_type = Column(SmallInteger)

    is_active = Column(Boolean)

    def __repr__(self):
        return u"<User: ({} {})>".format(self.id, self.name)

    def is_management(self):
        return self.user_type in [self.USER_EMPLOYEE, self.USER_ADMIN]

    def is_admin(self):
        return self.user_type == self.USER_ADMIN

编辑:

我发现 Base.metadata.sorted_tables 是空的。

1个回答

21

除了导入你的声明性Base类之外,你还需要导入所有的模型。像import project.models或其他包含所有模型类的模块一样。否则,由于env.py从未包含它们,你的Base.metadata将不会填充模型定义。


2
如果你和我一样,已经定义了表格,请确保重命名现有的表格,例如使用 _old 后缀,执行你的 alembic 生成,删除自动生成脚本中的额外 drop 语句(它会找到你重命名的表格并生成 drop/create 语句),最后将表格重新命名。可能应该有一个 --init 选项可以传递给自动生成,这样就不需要这么绕了... - smaudet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接