迁移被反复创建

migrations are getting created repeatedly

我已经创建了一些模型,当我 运行 python manage.py db migrate 命令时它会创建迁移文件,所以没问题。
python manage.py db upgrade 命令还在数据库中创建 table。
如果我再次 运行 python manage.py db migrate 命令,那么它将为我最近升级的那些模型创建迁移文件。
你能帮我解决一下吗

我觉得问题是manage.py。如果您按照 flask-migration 网站上的描述进行操作并将所有模型存储在此文件中 - flask-migration 只需获取这些模型并生成迁移并将始终执行此操作。您将标准命令包装在文件中,这就是问题所在。

如果你想修复它 - 将模型存储在另一个目录(或另一个文件)中,将它们添加到应用程序并使用命令 flask db migrate。在这种情况下,flask-migration 只会在第一次为模型生成迁移,对于其他模型,它会检测更改并仅为更改生成迁移。

但是要小心,flask-migration 不会看到所有的变化。来自网站:

The migration script needs to be reviewed and edited, as Alembic currently does not detect every change you make to your models. In particular, Alembic is currently unable to detect table name changes, column name changes, or anonymously named constraints. A detailed summary of limitations can be found in the Alembic autogenerate documentation.

我遇到了同样的问题,我已经解决了。

就我而言,获取当前 table 名称时出现问题。 (在 _autogen_for_tables((alembic/autogenerate/compare.py))

中调用 get_table_names 函数时

我在 mysql-connector 中使用 sqlalchemy。 mysql-connector return table 字节数组形式的信息。 所以我暂时改变了以下内容。 (base.py(sqlalchemy/dialects/mysql))

@reflection.cache
def get_table_names(self, connection, schema=None, **kw):
    """Return a Unicode SHOW TABLES from a given schema."""
    if schema is not None:
        current_schema = schema
    else:
        current_schema = self.default_schema_name

    charset = self._connection_charset
    if self.server_version_info < (5, 0, 2):
        rp = connection.execute(
            "SHOW TABLES FROM %s"
            % self.identifier_preparer.quote_identifier(current_schema)
        )
        return [
            row[0] for row in self._compat_fetchall(rp, charset=charset)
        ]
    else:
        rp = connection.execute(
            "SHOW FULL TABLES FROM %s"
            % self.identifier_preparer.quote_identifier(current_schema)
        )

        return [
            row[0]
            for row in self._compat_fetchall(rp, charset=charset)
            if row[1]  == "BASE TABLE"
        ]

@reflection.cache
def get_table_names(self, connection, schema=None, **kw):
    """Return a Unicode SHOW TABLES from a given schema."""
    if schema is not None:
        current_schema = schema
    else:
        current_schema = self.default_schema_name

    charset = self._connection_charset
    if self.server_version_info < (5, 0, 2):
        rp = connection.execute(
            "SHOW TABLES FROM %s"
            % self.identifier_preparer.quote_identifier(current_schema)
        )
        return [
            row[0] for row in self._compat_fetchall(rp, charset=charset)
        ]
    else:
        rp = connection.execute(
            "SHOW FULL TABLES FROM %s"
            % self.identifier_preparer.quote_identifier(current_schema)
        )

        return [
            row[0].decode("utf-8")
            for row in self._compat_fetchall(rp, charset=charset)
            if row[1].decode("utf-8")  == "BASE TABLE"
        ]