alickr
alickr
采纳率100%
2016-09-27 20:21 阅读 1.6k
已采纳

python使用SQLAlchemy的初级问题

代码:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:xxxxxx@localhost/flasky'

app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

db = SQLAlchemy(app)

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer,primary_key = True)
    name = db.Column(db.String(64), unique = True)
    users = db.relationship('User', backref = 'role')       #这行建立一对多的反向关系时出错

    def __repr__(self):
        return '<Role %r>' % self.name

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(64), unique = True)
    role_id = db.column(db.Integer, db.ForeignKey('roles.id'))

    def __repr__(self):
        return '<User %r>' % self.username

if __name__ == '__main__':
    app.run()

出错提示:
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Role.users - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

提示没有建立外键,但是我明明在User里面建立了一个叫role_id的外键,求解

__python版本是3.5.0 数据库是mysql

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    oyljerry oyljerry 2016-09-28 07:30

    把数据库的表,关系列出来看看
    同时检查一下sqlalchemy的语法是否用对了

    点赞 评论 复制链接分享

相关推荐