【问题标题】:SQLAlchemy User Many to Many RelationshipSQLAlchemy 用户多对多关系
【发布时间】: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


    【解决方案1】:

    db.Table主要用于两个不同实体之间存在Many to Many关系时。这里父母和孩子都是Users。

    在你的情况下,下面的代码就可以了:

    class User(db.Model):
        __tablename__ = 'users'
        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))
    
    
    class Parent(db.Model):
        __tablename__ = 'parents'
        child_id = db.Column(db.Integer, db.Foreignkey('users.id'))
        parent_id = db.Column(db.Integer, db.Foreignkey('users.id'))
        child = db.relationship('User', foreign_keys=[child_id], backref = 'parents')
    

    flask_sqlalchemy 写在SQLAlchemy 之上,SQLAlchemy 的网站上有一个很好的阐述这个问题here (Handling Multiple Join Paths)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 2019-06-22
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多