Flask-SQLAlchemy:没有链接这些表的外键

时间:2015-12-16 17:26:40

标签: python flask sqlalchemy flask-sqlalchemy

我正在使用Flask-SQLAlchemy和以下models.py

class DomainRoot(db.Model):
    # Int/Float fields
    id      = db.Column(db.Integer, primary_key=True)

    # String fields
    domain  = db.Column(db.String(64), index=True, unique=True)

    # DateTime fields
    created = db.Column(db.DateTime)
    updated = db.Column(db.DateTime)

    # ForeignKey relationships
    domain_paths = db.relationship('DomainPath', backref='domain_root', lazy='dynamic')

    def __repr__(self):
        return '<DomainRoot %r>' % (self.domain)

class DomainPath(db.Model):
    # Int/Float fields
    id          = db.Column(db.Integer, primary_key=True)

    # String fields
    domain_path = db.Column(db.String(256), index=True, unique=True)

    # DateTime fields
    created     = db.Column(db.DateTime)
    updated     = db.Column(db.DateTime)

    # ForeignKey fields
    domainroot_id = db.Column(db.Integer, db.ForeignKey('domainroot.id'))

    def __repr__(self):
        return '<DomainPath %r>' % (self.domain_path)

当我尝试查询DomainRoot对象时,出现错误:

InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Original exception was: Could not determine join condition between parent/child tables on relationship DomainRoot.domain_paths - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

据我所知,我添加了正确的外键字段。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

Flask-SQLAlchemy使用下划线自动生成表名domain_root。你引用domainroot没有下划线。

通常,在同一模型中定义fk和关系更容易,并避免使用字符串引用。

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

class DomainRoot(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class DomainPath(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    root_id = db.Column(db.ForeignKey(DomainRoot.id))
    root = db.relationship(DomainRoot, backref='paths')

db.create_all()
db.session.add(DomainRoot(paths=[DomainPath(), DomainPath()]))
db.session.commit()
print(DomainRoot.query.get(1).paths)
[<__main__.DomainPath object at 0x7fc27f443f28>, <__main__.DomainPath object at 0x7fc27f443fd0>]