如何在第一次迁移中插入一些种子数据?如果迁移不是最好的地方,那么最佳做法是什么?
"""empty message
Revision ID: 384cfaaaa0be
Revises: None
Create Date: 2013-10-11 16:36:34.696069
"""
# revision identifiers, used by Alembic.
revision = '384cfaaaa0be'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('list_type',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=80), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('job',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('list_type_id', sa.Integer(), nullable=False),
sa.Column('record_count', sa.Integer(), nullable=False),
sa.Column('status', sa.Integer(), nullable=False),
sa.Column('sf_job_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('compressed_csv', sa.LargeBinary(), nullable=True),
sa.ForeignKeyConstraint(['list_type_id'], ['list_type.id'], ), …Run Code Online (Sandbox Code Playgroud) 当我尝试创建数据库模式迁移时,我遇到了这个奇怪的错误.你能帮我弄清楚出了什么问题吗?
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
Run Code Online (Sandbox Code Playgroud)
我的模特:
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
Run Code Online (Sandbox Code Playgroud) 我正在使用SqlAlchemy和Flask-migrate进行数据库迁移.我已经成功init了DB和upgrade一次,但是当我删除了我的表列的一个,我设法migrate但是upgrade给了我以下错误:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near "DROP": syntax error [SQL: u'ALTER TABLE posts DROP COLUMN tags']
Run Code Online (Sandbox Code Playgroud)
我的models.py有一部分
class Post(db.Model):
__tabelname__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.UnicodeText)
# tags = db.Column(db.Unicode(32))
# I deleted this field, upgrade give me error
....
Run Code Online (Sandbox Code Playgroud)
然后我再次运行python manage.py db upgrade,错误改变了!
(venv)ncp@ubuntu:~/manualscore$ python manage.py db upgrade
INFO [alembic.migration] Context impl SQLiteImpl.
INFO [alembic.migration] Will assume non-transactional DDL.
INFO [alembic.migration] Running upgrade 555b78ffd5f -> 2e063b1b3164, add tag …Run Code Online (Sandbox Code Playgroud) 我在Python3下使用Flask开发了一个web应用程序.我在db migrate/upgrade上遇到postgresql枚举类型的问题.
我在模型中添加了一个"状态"列:
class Banner(db.Model):
...
status = db.Column(db.Enum('active', 'inactive', 'archive', name='banner_status'))
...
Run Code Online (Sandbox Code Playgroud)
生成的迁移python manage.py db migrate是:
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('banner', sa.Column('status', sa.Enum('active', 'inactive', 'archive', name='banner_status'), nullable=True))
def downgrade():
op.drop_column('banner', 'status')
Run Code Online (Sandbox Code Playgroud)
当我这样做时,python manage.py db upgrade我得到一个错误:
...
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) type "banner_status" does not exist
LINE 1: ALTER TABLE banner ADD COLUMN status banner_status
[SQL: 'ALTER TABLE banner ADD COLUMN status banner_status']
Run Code Online (Sandbox Code Playgroud)
为什么迁移不会创建类型"banner_status"?
我究竟做错了什么?
$ pip freeze
alembic==0.8.6
Flask==0.10.1
Flask-Fixtures==0.3.3
Flask-Login==0.3.2 …Run Code Online (Sandbox Code Playgroud) sqlalchemy sqlalchemy-migrate flask flask-sqlalchemy flask-migrate
我在文件中有以下模型listpull/models.py:
from datetime import datetime
from listpull import db
class Job(db.Model):
id = db.Column(db.Integer, primary_key=True)
list_type_id = db.Column(db.Integer, db.ForeignKey('list_type.id'),
nullable=False)
list_type = db.relationship('ListType',
backref=db.backref('jobs', lazy='dynamic'))
record_count = db.Column(db.Integer, nullable=False)
status = db.Column(db.Integer, nullable=False)
sf_job_id = db.Column(db.Integer, nullable=False)
created_at = db.Column(db.DateTime, nullable=False)
compressed_csv = db.Column(db.LargeBinary)
def __init__(self, list_type, created_at=None):
self.list_type = list_type
if created_at is None:
created_at = datetime.utcnow()
self.created_at = created_at
def __repr__(self):
return '<Job {}>'.format(self.id)
class ListType(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
def …Run Code Online (Sandbox Code Playgroud) 我将 Flask 与 Flask-SQLAlchemy 和 Flask-Migrate 一起使用来创建应用程序,但是当我尝试创建迁移时,什么也没有发生。
我在以下位置创建了两个表app/models.py:
from flask import current_app
from . import db
class Student(db.Model):
__tablename__ = 'students'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, nullable=False)
password_hash = db.Column(db.String(128))
def __init__(self, **kwargs):
super(Student, self).__init__(**kwargs)
def __repr__(self):
return '<Tutor {}>' % self.id
class Tutor(db.Model):
__tablename__ = 'tutors'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
def __init__(self, **kwargs):
super(Tutor, self).__init__(**kwargs)
def __repr__(self):
return '<Student %r>' % self.id
Run Code Online (Sandbox Code Playgroud)
然后我还有app/__init__.py以下代码:
from …Run Code Online (Sandbox Code Playgroud) 我已经使用SQLAlchemy设置了一个本地Postgres DB,并且无法提交我的第一个条目.我继续犯这个错误......
ProgrammingError: (ProgrammingError) relation "user" does not exist
LINE 1: INSERT INTO "user" (name, email, facebook_id, facebook_token...
Run Code Online (Sandbox Code Playgroud)
看起来这些字段与数据库中的字段不匹配.我正在尝试使用flask-migrate进行迁移,但是,当我运行时,$ python app.py db migrate我收到此错误...
raise util.CommandError("No such revision '%s'" % id_)
alembic.util.CommandError: No such revision '39408d6b248d'
Run Code Online (Sandbox Code Playgroud)
最好删除所有内容并从头开始,因为我似乎已经破坏了我的数据库设置和/或迁移,但我不知道如何.
更新:数据库现在已经开始工作(我删除并再次创建它).但是,我仍然在尝试运行迁移时遇到同样的错误,结果是"没有这样的修订'39408d6b248d'指的是从一个不相关的项目迁移.我重新安装了flask-migrate但同样的错误.
我正在研究一个烧瓶教程,我正在尝试运行一个创建数据库的脚本,而不是通过命令行来完成它.它使用SQLAlchemy-migrate包,但是当我尝试运行脚本时,它会产生ImportError.
这是终端输出:
Sean:app seanpatterson$ python ./db_create.py
Traceback (most recent call last):
File "./db_create.py", line 2, in <module>
from migrate.versioning import api
ImportError: No module named migrate.versioning
Run Code Online (Sandbox Code Playgroud)
这是db_create.py脚本:
#!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
Run Code Online (Sandbox Code Playgroud)
这是它引用的配置文件:
#!/usr/bin/env python
import os
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
Run Code Online (Sandbox Code Playgroud)
此应用程序正在使用虚拟环境运行.这是我在环境中安装的与之相关的模块:
sqlalchemy_migrate-0.7.2-py2.7.egg-信息
任何帮助赞赏
我在我的应用程序中使用Flask-Migrate,具有以下模型:
listpull/models.py
from datetime import datetime
from listpull import db
class Job(db.Model):
id = db.Column(db.Integer, primary_key=True)
list_type_id = db.Column(db.Integer, db.ForeignKey('listtype.id'),
nullable=False)
list_type = db.relationship('ListType',
backref=db.backref('jobs', lazy='dynamic'))
record_count = db.Column(db.Integer, nullable=False)
status = db.Column(db.Integer, nullable=False)
sf_job_id = db.Column(db.Integer, nullable=False)
created_at = db.Column(db.DateTime, nullable=False)
compressed_csv = db.Column(db.LargeBinary)
def __init__(self, list_type, created_at=None):
self.list_type = list_type
if created_at is None:
created_at = datetime.utcnow()
self.created_at = created_at
def __repr__(self):
return '<Job {}>'.format(self.id)
class ListType(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
def __init__(self, …Run Code Online (Sandbox Code Playgroud) sqlalchemy sqlalchemy-migrate flask flask-sqlalchemy flask-migrate
我一直在使用Flask-Migrate(Alembic)来更新我的数据库.我更新了我的models.py文件,但是我犯了一个错误.我运行了迁移并去升级数据库,但是我收到了这个错误:
sqlalchemy.exc.IntegrityError: (_mysql_exceptions.IntegrityError) (1215, 'Cannot add foreign key constraint') [SQL: u'\nCREATE TABLE topics (\n\tid INTEGER NOT NULL AUTO_INCREMENT, \n\t`subjectID` INTEGER, \n\ttopic VARCHAR(150) NOT NULL, \n\tPRIMARY KEY (id), \n\tFOREIGN KEY(`subjectID`) REFERENCES subjects (id)\n)\n\n']
Run Code Online (Sandbox Code Playgroud)
我所做的是db.Text取而代之的db.Integer是外键.
当我尝试运行新的迁移时,我得到了这个:
alembic.util.CommandError: Target database is not up to date.
Run Code Online (Sandbox Code Playgroud)
所以现在我被卡住了.我无法升级数据库,也无法运行迁移.我尝试使用以下内容降级到较旧的数据库版本:
python manage.py db downgrade --sql b877018671c:36949b1cca31
Run Code Online (Sandbox Code Playgroud)
但是当我运行时,python manage.py db current我得到了最新的数据库版本,我被困在其中.
有没有解决这个问题?谢谢.
flask-migrate ×10
python ×8
flask ×7
sqlalchemy ×5
alembic ×2
importerror ×1
postgresql ×1
python-3.x ×1