玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python Flask-SQLAlchemy报sqlalchemy.exc.NoForeignKeysError是什么

谢谢大家。
代码如下,总是会提示这个错误:

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Problem.tags - there are no foreign keys linking these tables via secondary table 'problem_tags'.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify 'primaryjoin' and 'secondaryjoin' expressions.
tags_table = db.Table('problem_tags',
    db.Column('problem_id', db.Integer, db.ForeignKey('problem.id')),
    db.Column('tag_id', db.Integer, db.ForeignKey('problemtag.id'))
    )
class ProblemTag(db.Model):
    id=db.Column(db.Integer, primary_key=True)
    name=db.Column(db.String(80))
    problems = db.relationship('Problem',secondary=tags_table,
                           backref=db.backref('tags', lazy='dynamic'))
    def __init__(self,name):
        self.name=name

    def __repr__(self):
        return "<Tag %r>" % self.name

class Problem(db.Model):
    id=db.Column(db.Integer, primary_key=True)
    title=db.Column(db.String(80))
    tags = db.relationship('ProblemTag',secondary=tags_table,
                           backref=db.backref('problems', lazy='dynamic'))

    def __init__(self,title,tags):
        self.title=title
        self.tags=tags

    def __repr__(self):
        return "<Problem %r>" % self.title

你的问题好像是problemtag.id找不到外码,这个是因为 Flask-SQLAlchemy 创建的实际表的名称不是problemtag, 而是problem_tag,可以在表中通过 __tablename__来指定表的名称。
另外多对多关系,只需要定义一边就可以了。

tags_table = db.Table('problem_tags',
                      db.Column('problem_id', db.Integer, db.ForeignKey('problem.id')),
                      db.Column('tag_id', db.Integer, db.ForeignKey('problemtag.id'))
)


class ProblemTag(db.Model):
    __tablename__ = 'problemtag'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    problems = db.relationship('Problem', secondary=tags_table,
                               backref=db.backref('tags', lazy='dynamic'))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "<Tag %r>" % self.name


class Problem(db.Model):
    __tablename__ = 'problem'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))


    def __init__(self, title, tags):
        self.title = title
        self.tags = tags

    def __repr__(self):
        return "<Problem %r>" % self.title

Many-to-many relationship 只需要在一边定义

参见
https://pythonhosted.org/Flask-SQLAlchemy/models.html#many-to-many-relationships

ProblemTagproblems去掉应该就可以

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd18904.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月24日 - 14时40分10秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules