如何在 SQLAlchemy 模型中使用 SQLAlchemy Utils

4 sqlalchemy sqlalchemy-utils

我正在尝试创建一个使用 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)
Run Code Online (Sandbox Code Playgroud)

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

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`
Run Code Online (Sandbox Code Playgroud)

我不得不尽量明确地告诉我使用像模块,和使用一个“内部”的实现,SQLAlchemy的

数据:如果我manualy导入sqlalchemy_utils/migrations/version/efae4166f832_.py并卸下automaticaly产生的长度sa.Column('id', sqlalchemy_utils.types.uuid.UUIDType(length=16), nullable=False)它的工作原理罚款

我使用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)`
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Obs:MySQL 引擎

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

小智 6

您只需添加:

import sqlalchemy_utils
Run Code Online (Sandbox Code Playgroud)

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

  • 将导入行添加到 script.py.mako 会自动将其添加到您生成的任何新迁移脚本中。如果在生成一些先前的迁移脚本后将导入行添加到 script.py.mako,则还必须手动将导入行添加到先前生成的脚本中。 (2认同)

小智 2

谢谢,Marco,但我已经修好了。我已将导入放入env.pyscript.py.makoimport sqlalchemy_utils中,我还放入了以下函数:

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
Run Code Online (Sandbox Code Playgroud)

在env.py内部以及我render_item=render_item在函数中设置的同一文件中run_migrations_online

context.configure(
    ...,
    render_item=render_item,
    ...
)
Run Code Online (Sandbox Code Playgroud)

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

操作的顺序很重要:

  1. export FLASK_APP=manage.py

  2. flask db init

  3. 按照上面的教程做

  4. flask db migrate

  5. flask db upgrade