与继承的类有多对一的关系

时间:2015-07-24 18:46:19

标签: python mysql flask sqlalchemy flask-sqlalchemy

我正在学习Flask并且正在构建一个地址簿应用程序。使用SQLAlchemy实现我的模型时出现以下错误:

  

sqlalchemy.exc.AmbiguousForeignKeysError:无法确定关系Company.contacts上的父/子表之间的连接条件 - 有多个链接表的外键路径。指定' foreign_keys'参数,提供应列为包含父表的外键引用的列的列表。

class Person(db.Model):
    __tablename__ = 'person'

    id = db.Column(db.Integer, primary_key=True)
    address = db.relationship('Address',
                              secondary=address_person,
                              backref=db.backref('persons', lazy='dynamic'),
                              lazy='dynamic')
    projects = db.relationship('Project',
                               secondary="project_person_link",
                               backref=db.backref('persons', lazy='dynamic'),
                               lazy='dynamic')
    phonenumbers = db.relationship('Phone', backref='Phonenumbers', lazy='dynamic')
    mails = db.relationship('Mail', backref='Mails', lazy='dynamic')


class Company(Person):
    id = db.Column(db.Integer, db.ForeignKey("person.id"), primary_key=True)

    title = db.Column(db.String(250))
    name = db.Column(db.String(250))
    group_id = db.Column(db.Integer, db.ForeignKey('group.id'))

    contacts = db.relationship('Contact', backref="company", lazy='dynamic')


class Contact(Person):
    id = db.Column(db.Integer, db.ForeignKey("person.id"), primary_key=True)
    title = db.Column(db.String(250))
    name = db.Column(db.String(250))
    christmas_card = db.Column(db.Boolean)
    picture = db.Column(db.String(250))

    company_id = db.Column(db.Integer, db.ForeignKey('company.id'))

我并没有真正看到我做错了什么,对任何提示都有帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

我通过包含一个primaryjoin参数修复了我的问题。

class Company(Person):
    id = db.Column(db.Integer, db.ForeignKey("person.id"), primary_key=True)
    title = db.Column(db.String(250))
    name = db.Column(db.String(250))
    group_id = db.Column(db.Integer, db.ForeignKey('group.id'))

    contacts = db.relationship('Contact', backref="company", primaryjoin="Company.id==Contact.company_id")