如何在 SQLAlchemy 模型中使用 SQLAlchemy Utils

How to use SQLAlchemy Utils in a SQLAlchemy model

我正在尝试创建一个使用 UUID 作为主键的用户模型:

from src.db import db # SQLAlchemy instance

import sqlalchemy_utils

import uuid


class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(sqlalchemy_utils.UUIDType(binary=True), primary_key=True, nullable=False)

但是当我生成迁移时,我收到:

File "/home/pc/Downloads/project/auth/venv/lib/python3.6/site-packages/alembic/runtime/environment.py", line 836, in run_migrations
    self.get_context().run_migrations(**kw)
  File "/home/pc/Downloads/project/auth/venv/lib/python3.6/site-packages/alembic/runtime/migration.py", line 330, in run_migrations
step.migration_fn(**kw)
  File "/home/pc/Downloads/project/auth/migrations/versions/efae4166f832_.py", line 22, in upgrade
    sa.Column('id', sqlalchemy_utils.types.uuid.UUIDType(length=16), nullable=False),
NameError: name 'sqlalchemy_utils' is not defined`

我曾尝试明确告知我正在使用的模块,例如 this and use a 'internal' implementation that SQLAlchemy

Obs:如果我在 /migrations/version/efae4166f832_.py 中手动导入 sqlalchemy_utils 并删除自动生成的长度 sa.Column('id', sqlalchemy_utils.types.uuid.UUIDType(length=16), nullable=False) 它有效 fine

我使用 generate.py 脚本生成迁移:

from src import create_app

from src.db import db

from flask_migrate import Migrate

# Models

from src.user.models.user import User

app = create_app()

migrate = Migrate(app, db)`

观察:MySQL引擎

我希望当我生成迁移时它会生成一个用户模型,该模型使用从 SQLAlchemy Utils 实现的 UUID 作为主键

您只需添加:

import sqlalchemy_utils

到您的 script.py.mako 内部迁移文件夹

谢谢,Marco,但我已经修复了它。我把 import import sqlalchemy_utils 放在 env.pyscript.py.mako 里面,我还把下面的函数:

def render_item(type_, obj, autogen_context):
    """Apply custom rendering for selected items"""

    if type_ == "type" and isinstance(obj, sqlalchemy_utils.types.uuid.UUIDType):
        # Add import for this type
        autogen_context.imports.add("import sqlalchemy_utils")

        autogen_context.imports.add("import uuid")

        return "sqlalchemy_utils.types.uuid.UUIDType(), default=uuid.uuid4"

    # Default rendering for other objects
    return False

env.py 和同一个文件中,我在函数 run_migrations_online:

中设置了 render_item=render_item
context.configure(
    ...,
    render_item=render_item,
    ...
)

我研究过自动执行此操作,但找不到任何可以帮助我的东西。

操作顺序很重要:

  1. export FLASK_APP=manage.py

  2. flask db init

  3. 做上面的教程

  4. flask db migrate

  5. flask db upgrade

import sqlalchemy_utils 行添加到新创建的 migrations/versions/{hash}_my_comment.py 文件中。但是,这只会解决迁移的特定步骤的问题。如果您希望对引用 sqlalchemy_utils 的列进行大量更改,您可能应该像 Walter 的建议那样做一些更可靠的事情。尽管如此,看起来您可能需要添加代码以正确处理您最终使用的每种列类型。

注意:尽管在多个地方看到了将导入行添加到 script.py.mako 文件的建议,但这对我不起作用。

script.py.mako 文件中添加 import sqlalchemy_utils 将自动在所有生成的迁移文件中导入此行并解决问题。

from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
${imports if imports else ""}