【发布时间】:2015-05-14 04:38:39
【问题描述】:
我正在使用 Flask + Alembic + Sqlalchemy。我想创建两个表并使用它。首先,我运行 alembic 脚本:
"""add table insurace_bands and insurace_discounts
Revision ID: 39ba7ec3428
Revises: 18468fbedbac
Create Date: 2015-05-12 09:10:05.175513
"""
# revision identifiers, used by Alembic.
revision = '39ba7ec3428'
down_revision = '18468fbedbac'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('insurance_bands',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=1024), nullable=False),
sa.Column('product_price', sa.Numeric(precision=6, scale=2)),
sa.Column('monthly_price', sa.Numeric(precision=6, scale=2)),
sa.Column('active', sa.Boolean(), nullable=False, server_default='1'),
sa.PrimaryKeyConstraint('id')
)
op.create_table('insurance_discounts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=1024), nullable=False),
sa.Column('min_products', sa.Integer()),
sa.Column('max_products', sa.Integer()),
sa.Column('discount', sa.Numeric(precision=6, scale=2)),
sa.Column('active', sa.Boolean(), nullable=False, server_default='1'),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table(
'insurance_bands'
)
op.drop_table(
'insurance_discounts'
)
这个脚本运行正常。然后,我创建了两个这样的模型:
# -*- coding: utf-8 -*-
"""
admin.insurance_brands.models
~~~~~~~~~~~~~~~~~~~~~
insurance brand models
"""
from ..core import db
from ..helpers import JsonSerializer
class InsuranceBandJsonSerializer(JsonSerializer):
__json_public__ = ['id', 'name', 'product_price', 'monthly_price', 'active']
class InsuranceBand(InsuranceBandJsonSerializer, db.Model):
__tablename__ = 'insurance_bands'
id = db.Column(db.Integer(), primary_key=True),
name = db.Column(db.Unicode(1024)),
product_price = db.Column(db.Numeric(precision=6, scale=2)),
monthly_price = db.Column(db.Numeric(precision=6, scale=2)),
active = db.Column(db.Boolean, default=True)
class InsuranceDiscountJsonSerializer(JsonSerializer):
__json_public__ = ['id', 'name', 'min_products', 'max_products', 'active']
class InsuranceDiscount(InsuranceDiscountJsonSerializer, db.Model):
__tablename__ = 'insurance_discounts'
id = db.Column(db.Integer(), primary_key=True),
name = db.Column(db.Unicode(1024)),
min_products = db.Column(db.Integer()),
max_products = db.Column(db.Integer()),
active = db.Column(db.Boolean, default=True)
但是当我运行服务器:python wsgi.py 时,它会抛出错误:
sqlalchemy.exc.ArgumentError: Mapper Mapper|InsuranceBand|insurance_bands 无法为映射表“insurance_bands”组装任何主键列
似乎模型没有主键,但我定义了它。
谁能帮帮我。提前致谢。
【问题讨论】:
-
您可以尝试删除字段声明末尾的逗号并尝试吗?
-
@JRajan,啊,你是对的,我的错。非常感谢:D。
标签: python flask-sqlalchemy alembic