Python + Flask-SQLAlchemy

时间:2016-01-23 00:27:09

标签: python flask-sqlalchemy

我试图创建一个家谱,但我对数据模型有点麻烦。我有一个表需要以两种方式引用自己,一个用于父< - >孩子的关系,以及配偶关系的关系。我尝试了下面的代码,但我收到的错误是:

  

sqlalchemy.exc.NoReferencedTableError:与之关联的外键   专栏' spouses.so2_id'找不到表'成员'用哪个来   生成一个外键来定位列' member_id'

有人会有任何指导吗?我试图阅读Adjacency List Relationships上的文档,但有点迷失。感谢您提供任何帮助!

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

# association table for parents<->children
children = db.Table('children',
                db.Column('child_id', db.Integer, db.ForeignKey('member.member_id')),
                db.Column('parent_id', db.Integer, db.ForeignKey('member.member_id'))
                )

# association table for spouses
spouses = db.Table('spouses',
               db.Column('so1_id', db.Integer, db.ForeignKey('member.member_id')),
               db.Column('so2_id', db.Integer, db.ForeignKey('member.member_id'))
               )


class Member(db.Model):
    """Node within the family tree."""

    __tablename__ = "members"

    member_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    first_name = db.Column(db.String(60), nullable=False)
    last_name = db.Column(db.String(40), nullable=False)
    eng_title = db.Column(db.String(20), nullable=True)
    alt_name = db.Column(db.String(50), nullable=True)
    lineage = db.Column(db.String(15), nullable=True)
    deceased = db.Column(db.Boolean, nullable=True)
    image_url = db.Column(db.String(80), nullable=True)
    parents = db.relationship('Member',
                          secondary=children,
                          primaryjoin=(children.c.child_id == member_id),
                          secondaryjoin=(children.c.parent_id == member_id),
                          backref=db.backref('children', lazy='dynamic'),
                          lazy='dynamic')
    spouse = db.relationship('Member',
                         secondary=spouses,
                         primaryjoin=(spouses.c.so1_id == member_id),
                         secondaryjoin=(spouses.c.so2_id == member_id),
                         backref=db.backref('spouses', lazy='dynamic'),
                         lazy='dynamic')

0 个答案:

没有答案