我正在关注Flask 大型教程。在我尝试将几何列添加到数据库之前,这一切都运行良好。请注意,它在 Post 类中,称为位置。
#! model.py
from app import db
from geoalchemy2 import Geometry
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
def __repr__(self):
return '<User %r>' % (self.nickname)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
location = db.Column(Geometry('POINT'))
def __repr__(self):
return '<Post %r>' % (self.body)
然后我使用了教程中给出的 db_migrate.py,但是得到一个错误,说名称“几何”没有定义。这是 db_migrate.py 中的代码:
#!flask/bin/python
import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
migration = SQLALCHEMY_MIGRATE_REPO + ('/versions/%03d_migration.py' % (v+1))
tmp_module = imp.new_module('old_model')
old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
exec(old_model, tmp_module.__dict__)
script = api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, tmp_module.meta, db.metadata)
open(migration, "wt").write(script)
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print('New migration saved as ' + migration)
print('Current database version: ' + str(v))
然后我在上面代码生成的文件“/versions/%03d_migration.py”中发现,Geometry 没有被导入。所以我加了
from geoalchemy2 import Geometry
手动,然后我运行 db_update.py 并收到以下错误。
sqlalchemy.exc.OperationalError: (OperationalError) near "POINT": syntax error u'\nALTER TABLE post ADD location geometry(POINT,-1)' ()
这是 db_upgrade.py 的代码:
#!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print('Current database version: ' + str(v))
我不知道这次该怎么办。
所以我的问题是: 1. 我可以对 db_migrate.py 进行任何更改,以便“/versions/%03d_migration.py”自动导入 Geometry 类吗?2.不管1,如何添加几何列并迁移数据库?
非常感谢~!