【发布时间】:2018-02-26 05:54:54
【问题描述】:
我正在研究一种用户结构,其中用户可以拥有由用户对象组成的父母和孩子。我一直在尝试让以下内容在 SQLAlchemy 和 Flask 中以多种不同的方式工作。
这是一个我想如何构建它的示例:
UserTable
id | name
---+-----
1 | Kim
2 | Tammy
3 | John
4 | Casey
5 | Kyle
UserRelationship
id | parent_user_id | child_user_id
---+----------------+---------------
1 | 1 | 2
2 | 1 | 3
3 | 4 | 2
Kim 是 Tammy 和 John 的父母。凯西是塔米的父母。塔米是金和凯西的孩子。约翰是金的孩子。凯尔没有孩子也没有父母。
我的错误是:
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition
between parent/child tables on relationship User.parents - there are multiple
foreign key paths linking the tables via secondary table 'user_relationship'.
Specify the 'foreign_keys' argument, providing a list of those columns which
should be counted as containing a foreign key reference from the secondary
table to each of the parent and child tables.
我的model.py 文件如下所示:
user_relationship = db.Table(
'user_relationship',
db.Model.metadata,
db.Column('child_user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('parent_user_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False)
email = db.Column(db.String(120), unique=True)
pwdhash = db.Column(db.String(54))
parents = relationship('User',
secondary=user_relationship,
backref=db.backref('children'),
cascade="all,delete")
这可能不是在 Flask 或 SQLAlchemy 中处理多对多层次用户关系的最佳方式。任何关于如何构建它的见解都会很棒。
谢谢
【问题讨论】:
标签: python flask flask-sqlalchemy